Introduction to type Constraints in PHP, Introduction to PHP type constraints
Type constraints can be implemented in PHP class methods and functions, but parameters can only specify classes, arrays, interfaces, callable four types, parameters can default to null,php and cannot constrain scalar types or other types.
The following example:
Copy the Code code as follows:
<?php
Class Test
{
Public function Test_array (array $arr)
{
Print_r ($arr);
}
Public Function Test_class (Test1 $test 1 = null)
{
Print_r ($test 1);
}
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 $test 1 = null)
{
}
}
Class test1{}
$test = new test ();
A catch fatal error is thrown when the parameters of a function call are inconsistent with the defined parameter type.
$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 do you constrain scalar types?
The SPL types extension is provided in the PECL Extension library to implement Interger, float, bool, enum, String type constraints.
Copy the Code code 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;
/*
Operation Result:
Value not an integer
94
*/
SPL types will reduce some flexibility and performance, think twice in the actual project.
http://www.bkjia.com/PHPjc/997904.html www.bkjia.com true http://www.bkjia.com/PHPjc/997904.html techarticle PHP type Constraints introduced, PHP type constraints introduced PHP class methods and functions can implement type constraints, but the parameters can only specify classes, arrays, interfaces, callable four types, parameters can be tacitly ...