Type constraints can be implemented in PHP class methods and functions, but parameters can only specify classes, arrays, interfaces, and callables Four types, parameters can default to NULL, PHP cannot constrain scalar types or other types.
Example below:
Copy code The code is as follows:
class Test
{
Public function test_array(array $arr)
{
print_r($arr);
}
Public function test_class(Test1 $test1 = null)
{
print_r($test1);
}
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 $test1 = NULL)
{
}
}
class Test1{}
$test = new Test();
//When the parameters of the function call are inconsistent with the defined parameter types, a catchable fatal error will be 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 to constrain scalar types?
The PECL extension library provides SPL Types extension to implement interger, float, bool, enum, and string type constraints.
Copy code 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 ;
/*
Running result:
Value not an integer
94
*/
SPL Types will reduce certain flexibility and performance, so think twice in actual projects.