Description of type hint (hinting) function in PHP, typehinting
Overview
Starting with PHP5, we can use type hints to specify the type of arguments the function receives when defining a function. If the type of the parameter is specified when the function is defined, then when we call the function, if the type of the argument does not match the specified type, then PHP generates a fatal level of error (Catchable-fatal-error).
Class name and array
When defining a function, PHP supports only two types of declarations: class name and array. Class Name Table name the arguments that are received by this parameter are objects instantiated by the corresponding class, and the array indicates that the received argument is of the array type. Here is an example:
Copy the Code code as follows:
function demo (array $options) {
Var_dump ($options);
}
When defining the demo () function, the parameter type that the function receives is specified as an array. If we call the function, the passed parameter is not an array type, such as a call like this:
Copy the Code code as follows:
$options = ' options ';
Demo ($options);
Then the following error will be generated:
Copy the Code code as follows:
Catchable fatal Error:argument 1 passed to Demo () must is of the type array, string given,
You can use NULL as the default parameter
Attention
It is important to note that PHP supports only two types of type declarations, and that any other scalar type declarations are not supported, such as the following code will produce an error:
Copy the Code code as follows:
function Demo (string $str) {
}
$str = "Hello";
Demo ($STR)
When we run the above code, the string is treated as a class name, so the following error is reported:
Catchable fatal Error:argument 1 passed to Demo () must is an instance of string, string given,
Summarize
Type declarations are also a step forward in PHP object-oriented, especially when capturing exceptions of a specified type.
You can also increase the readability of your code by using a type declaration.
However, because PHP is a weakly typed language, the use of type declarations is contrary to the original intent of PHP design.
In the end use or do not use type declaration, we have a different opinion, Ben Rookie not:).
http://www.bkjia.com/PHPjc/1024914.html www.bkjia.com true http://www.bkjia.com/PHPjc/1024914.html techarticle Introduction to type hinting in PHP, typehinting overview Starting with PHP5, we can use type hints to specify the type of arguments the function receives when defining a function. If you are in a definite ...