PHP is a weak type. Its characteristic is that there is no need to specify a type for the variable, and any type can be stored afterwards. However, in the new syntax of php, in some specific occasions, for some Specific types can also be grammatically constrained.
Specific occasions: formal parameter variables of functions (methods)
Specific types: object type (class name), interface type (interface name), array Type (array), function type (callable)
This article mainly introduces Type constraints in PHPIntroduction, type constraints can be implemented in PHP class methods and functions, However, parameters can only specify four types: class, array, interface, and callable. Parameters can default to NULL. PHP cannot constrain scalar types or other types. Friends in need can refer to the following
The following example:
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 the scalar type?
The PECL extension library provides 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 ; /* 运行结果: Value not an integer 94 */
PS: SPL Types will reduce certain flexibility and performance, so think twice in actual projects.
The above is the detailed content of Introduction to type constraints in php. For more information, please follow other related articles on the PHP Chinese website!