Home  >  Article  >  Backend Development  >  PHP object-oriented-detailed example code of type constraints

PHP object-oriented-detailed example code of type constraints

黄舟
黄舟Original
2017-03-27 09:52:101268browse

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, ......){
    //....}

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);//没问题
?>

Running result:

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

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!

Statement:
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