Home > Article > Backend Development > Introduction to type constraints in php
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:
<?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(); //函数调用的参数与定义的参数类型不一致时,会抛出一个可捕获的致命错误。 $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 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!