PHP object-oriented-detailed example code of type constraints

黄舟
Release: 2023-03-07 06:24:01
Original
1228 people have browsed it

What is a typeConstraint

It is a requirement that a certain variable can only use (accept, store) a certain specified Data type; PHP is a "weakly typed language" and usually does not support type constraints; correspondingly, for a strongly typed language, type constraints are its "basic features".

In php, only partial type constraints are supported

In php, only type constraint targets are supported on the formal parameters of functions (or methods). The form is as follows:

function 方法名( [要求使用的类型] $p1, [要求使用的类型] $p2, ......){
    //....}
Copy after login

Description:

  1. When defining a function (method), a formal parameter can be used Type constraints may not be used;

  2. If type constraints are used, the corresponding actual parameter data must be of the required type;

  3. The type constraints that can be used are only available in the following situations:

    1. Array: array

    2. Object: Use the name of the class, and the actual parameters passed must be instances of the class

    3. Interface: Use the name of the interface, and the actual parameters passed must be the implementation of the class Instance of the interface class

<?php
//演示类型约束
interface USB{} //接口
class A{}   //类
class B implements USB{}    //实现了USB接口的类

function f1($p1, array $p2, A $p3, USB $P4){
    echo "<br />没有约束的p1:" . $p1;
    echo "<br />要求是数组的p2:" ;
        print_r($p2);
    echo "<br />要求是类A的对象:";
        var_dump($p3);
    echo "<br />要求是实现实现了USB接口的对象:";
        var_dump($P4);
}

$obj1 = new A();
$obj2 = new B();
$arr = array();

//演示各种形式的函数调用
//f1(1.2, 1, $obj1, $obj2);//报错,第二个参数不是数组类型,Argument 2 passed to f1() must be an array, integer give
//f1(1, $arr, $obj1, $obj1);//报错,第四个参数,Argument 4 passed to f1() must implement interface USB, instance of A given
f1(1.2, $arr, $obj1, $obj2);//没问题
?>
Copy after login

Running result:

没有约束的p1:1.2
要求是数组的p2:Array ( )
要求是类A的对象:object(A)[1]
要求是实现实现了USB接口的对象:object(B)[2]
Copy after login

The above is the detailed content of PHP object-oriented-detailed example code of type constraints. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!