PHP5 can use type constraints. Function parameters can be specified as objects (specify the class name in the function prototype), interfaces, arrays (starting with PHP5.1), or callable (starting with PHP5.4 ). However, if NULL is used as the default value of the parameter, NULL can still be used as the real parameter when calling the function. PHP 5 can use type constraints. Function parameters can be specified as objects (specify the class name in the function prototype), interfaces, arrays (from PHP 5.1) or callable (from PHP 5.4 ). However, if NULL is used as the default value of the parameter, NULL can still be used as the real parameter when calling the function.
If a class or interface specifies a type constraint, the same applies to all its subclasses or implementations.
Type constraints cannot be used for scalar types such as int or string. Traits is not allowed.
Example #1 type constraints
Var;}/*** another test function * The first parameter must be an array */public function test_array (array $ input_array) {print_r ($ input_array );} /*** The first parameter must be of the recursive type */public function test_interface (Traversable $ iterator) {echo get_class ($ iterator );} /*** The first parameter must be of the callback type */public function test_callable (callable $ callback, $ data) {call_user_func ($ callback, $ data );}} // OtherClass class definition class OtherClass {public $ var = 'Hello world' ;}?>
When a function call parameter is different from the defined parameter type, a fatal error is thrown.
Test ('Hello'); // fatal error: The first parameter must be an instance of the OtherClass $ foo = new stdClass; $ myclass-> test ($ foo ); // fatal error: The first parameter cannot be null $ myclass-> test (null); // correct: output Hello World $ myclass-> test ($ otherclass ); // fatal error: The first parameter must be an array $ myclass-> test_array ('a string'); // correct: output array $ myclass-> test_array (array ('A', 'B', 'C'); // correct: output ArrayObject $ myclass-> test_interface (new ArrayObject (array (); // correct: output int (1) $ myclass-> test_ca Llable ('Var _ dump', 1);?>
Type constraints are not only used in member functions of the class, but also in functions:
Var ;}// correct $ myclass = new MyClass; MyFunction ($ myclass) ;?>
Type constraints allow NULL values: