This article mainly introduces the type constraint in PHP, PHP class methods and functions can be implemented type constraints, but the parameters can only specify classes, arrays, interfaces, callable four types, parameters can default to null,php and can not constrain the scalar type or other types, the need for friends can refer to the
Type constraints can be implemented in PHP's class methods and functions, but parameters can only specify classes, arrays, interfaces, callable four types, and parameters can default to null,php and cannot constrain scalar types or other types.
The following example:
The code is as follows:
Class Test
{
Public function Test_array (array $arr)
{
Print_r ($arr);
}
Public Function Test_class (Test1 $test 1 = null)
{
Print_r ($test 1);
}
Public Function test_callable (callable $callback, $data)
{
Call_user_func ($callback, $data);
}
Public Function Test_interface (traversable $iterator)
{
Print_r (Get_class ($iterator));
}
Public Function Test_class_with_null (Test1 $test 1 = null)
{
}
}
Class test1{}
$test = new test ();
When a function calls an argument that is inconsistent with a defined parameter type, a fatal error that can be caught is thrown.
$test->test_array (Array (1));
$test->test_class (New Test1 ());
$test->test_callable (' Print_r ', 1);
$test->test_interface (New Arrayobject (Array ()));
$test->test_class_with_null ();
So how do you constrain scalar types?
The SPL types extension implements Interger, float, bool, enum, String type constraints in the PECL extension library.
The code is as follows:
$int = new Splint (94);
try {
$int = ' Try to cast a string value for fun ';
catch (Unexpectedvalueexception $uve) {
echo $uve-> getMessage (). Php_eol;
}
Echo $int. Php_eol;
/*
Run Result:
Value not an integer
94
*/
SPL types will reduce a certain amount of flexibility and performance in the actual project to reconsider.