您好,欢迎访问一九零五行业门户网

如何使用类型约束来限定php函数类型

php 5 可以使用类型约束。函数的参数可以指定必须为对象类型或数组类型或递归类型或回调类型的数据;
<?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 = 'hello world'; } ?>
函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。
<?php // 两个类的对象 $myclass = new myclass; $otherclass = new otherclass; // 致命错误:第一个参数必须是 otherclass 类的一个对象 $myclass->test('hello'); // 致命错误:第一个参数必须为 otherclass 类的一个实例 $foo = new stdclass; $myclass->test($foo); // 致命错误:第一个参数不能为 null $myclass->test(null); // 正确:输出 hello world $myclass->test($otherclass); // 致命错误:第一个参数必须为数组 $myclass->test_array('a string'); // 正确:输出数组 $myclass->test_array(array('a', 'b', 'c')); // 正确:输出 arrayobject $myclass->test_interface(new arrayobject(array())); // 正确:输出 int(1) $myclass->test_callable('var_dump', 1); ?>
类型约束不只是用在类的成员函数里,也能使用在函数里。
<?php // 如下面的类 class myclass { public $var = 'hello world'; } /** * 测试函数 * 第一个参数必须是 myclass 类的一个对象 */ function myfunction (myclass $foo) { echo $foo->var; } // 正确 $myclass = new myclass; myfunction($myclass); ?>
类型约束允许 null 值
<?php /* 接受 null 值 */ function test(stdclass $obj = null) { } test(null); test(new stdclass); ?>
以上就是如何使用类型约束来限定php函数类型的详细内容。
其它类似信息

推荐信息