Description of type constraints in PHP and description of PHP type constraints. Description of type constraints in PHP. description of PHP type constraints: class methods and functions in PHP can implement type constraints, but parameters can only specify four types: Class, array, interface, and callable, introduction to the type constraints in the parameter's default PHP, and introduction to the PHP type constraints
PHP class methods and functions can implement type constraints, but parameters can only specify four types: Class, array, interface, and callable. the default value of a parameter is NULL, PHP does not restrict the scalar type or other types.
Example:
The code is as follows:
<? Php
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 ();
// If the parameter of a function call is different from the defined parameter type, a fatal error 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 are constraints on scalar types?
The PECL Extension Library provides the SPL Types extension to implement interger, float, bool, enum, and string type constraints.
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 reduces flexibility and performance, so you can think twice in your project.
Class methods and functions in PHP can implement type constraints, but parameters can only specify four types: Class, array, interface, and callable...