Overview
Starting with PHP5, we can use type hints to specify the type of arguments that the function receives when defining the 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, PHP generates a fatal level error (catchable fatal error).
Class name and array
When you define a function, PHP supports only two types of declarations: the class name and the array. Class Name Table name the argument received by this parameter is an object instantiated for the corresponding class, which indicates that the received argument is an array type. Here is an example:
Copy Code code as follows:
function demo (array $options) {
Var_dump ($options);
}
When defining the demo () function, the parameter types received by the function are specified as arrays. If we call a function, the incoming argument is not an array type, such as a call like the following:
Copy Code code as follows:
$options = ' options ';
Demo ($options);
Then the following error occurs:
Copy 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
One thing to be particularly aware of is that PHP supports only two types of type declarations, and any other scalar type declarations are not supported, for example, the following code will produce an error:
Copy Code code as follows:
function Demo (string $str) {
}
$str = "Hello";
Demo ($STR)
When we run the above code, 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 for PHP object-oriented, especially if you are capturing a specific type of exception.
You can also increase the readability of your code by using type declarations.
However, because PHP is a weakly typed language, using a type declaration is inconsistent with the original purpose of PHP design.
Whether to use or not to use the type declaration, we have a different opinion, this rookie does not:).