Home >Backend Development >PHP Tutorial >How to use type constraints to qualify php function types

How to use type constraints to qualify php function types

伊谢尔伦
伊谢尔伦Original
2017-06-26 14:23:422679browse

PHP 5 can use type constraints. Parameters of the function can specify data that must be object type or array type or recursive type or callback type ;

<?php
//如下面的类
class MyClass
{
    /**
     * 测试函数
     * 第一个参数必须为 OtherClass 类的一个对象
     */
    public function test(OtherClass $otherclass) {
        echo $otherclass->var;
    }
    /**
     * 另一个测试函数
     * 第一个参数必须为数组 
     */
    public function test_array(array $input_array) {
        print_r($input_array);
    }
}
    /**
     * 第一个参数必须为递归类型
     */
    public function test_interface(Traversable $iterator) {
        echo get_class($iterator);
    }
    
    /**
     * 第一个参数必须为回调类型
     */
    public function test_callable(callable $callback, $data) {
        call_user_func($callback, $data);
    }
}
// OtherClass 类定义
class OtherClass {
    public $var = &#39;Hello World&#39;;
}
?>

When the parameters of the function call are inconsistent with the defined parameter types, a catchable fatal error will be thrown.

<?php
// 两个类的对象
$myclass = new MyClass;
$otherclass = new OtherClass;
// 致命错误:第一个参数必须是 OtherClass 类的一个对象
$myclass->test(&#39;hello&#39;);
// 致命错误:第一个参数必须为 OtherClass 类的一个实例
$foo = new stdClass;
$myclass->test($foo);
// 致命错误:第一个参数不能为 null
$myclass->test(null);
// 正确:输出 Hello World 
$myclass->test($otherclass);
// 致命错误:第一个参数必须为数组
$myclass->test_array(&#39;a string&#39;);
// 正确:输出数组
$myclass->test_array(array(&#39;a&#39;, &#39;b&#39;, &#39;c&#39;));
// 正确:输出 ArrayObject
$myclass->test_interface(new ArrayObject(array()));
// 正确:输出 int(1)
$myclass->test_callable(&#39;var_dump&#39;, 1);
?>

Type constraints are not only used in member functions of classes, but can also be used in functions.

<?php
// 如下面的类
class MyClass {
    public $var = &#39;Hello World&#39;;
}
/**
 * 测试函数
 * 第一个参数必须是 MyClass 类的一个对象
 */
function MyFunction (MyClass $foo) {
    echo $foo->var;
}
// 正确
$myclass = new MyClass;
MyFunction($myclass);
?>

Type constraints allow NULL values

<?php
/* 接受 NULL 值 */
function test(stdClass $obj = NULL) {
}
test(NULL);
test(new stdClass);
?>

The above is the detailed content of How to use type constraints to qualify php function types. 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