Introduction to type constraints in PHP
This article mainly introduces the type constraints in PHP. PHP class methods and functions can implement type constraints, but the parameters can only specify four types: Class, array, interface, and callable, the parameter can be NULL by default. PHP does not restrict the scalar type or other types. For more information, see
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:
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.