Home >Backend Development >PHP Tutorial >[php classes and objects] type constraints
The content of this article is about [php classes and objects] type constraints, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
Type constraints
PHP 5 can use type constraints.
The parameters of the function can be specified as:
Object (specify the name of the class in the function prototype)
Interface
Array (PHP 5.1)
callable (PHP 5.4)
If using NULL as The default value of the parameter, then NULL can still be used as the actual parameter when calling the function.
If a class or interface specifies a type constraint, so do all its subclasses or implementations.
Type constraints cannot be used for scalar types such as int or string. Traits are not allowed either.
Example #1 类型约束示例 <?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'; } ?>
Related recommendations:
[php classes and objects] object copy
[php classes and objects]magic method
【php classes and objects】Traversal
The above is the detailed content of [php classes and objects] type constraints. For more information, please follow other related articles on the PHP Chinese website!