PHP 5 can use type constraints. The parameters of a function can specify data that must be an object type or an array type or a recursive type or a callback type;
<?php//class myclass{ /** * Test function * The first parameter must be an object of the Otherclass class * * Public function test ( Otherclass $otherclass) { echo $otherclass->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 a recursive type * /Public Function test_interface (traversable $iterator) { echo get_class ($ iterator); } /** * The first parameter must be a callback type */public function test_callable (callable $callback, $data) { Call_user_func ( $callback, $data);} } Otherclass class Otherclass {public $var = ' Hello world ';}? >
A catch fatal error is thrown when the parameters of a function call are inconsistent with the defined parameter type.
<?php//object of two classes $myclass = new MyClass; $otherclass = new otherclass;//fatal error: The first argument must be an object of the Otherclass class $myclass->test (' hello ');//Fatal error: The first parameter must be an instance of the Otherclass class $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_callable (' Var_dump ', 1);? >
Type constraints are not only used in the member functions of a class, but also in functions.
<?php//class MyClass {public $var = ' Hello world ';} /** * Test function * The first parameter must be an object of the MyClass class */function MyFunction (MyClass $foo) { echo $foo->var;} Correct $myclass = new MyClass; MyFunction ($myclass);? >
Type constraints allow NULL values
<?php/* accepts NULL values */function Test (StdClass $obj = null) {}test (null); Test (new StdClass);?