Description of the type hinting function in PHP, typehinting
Overview
From PHP5, we can use the type prompt to specify the parameter type received by the function when defining the function. If the parameter type is specified when the function is defined, if the real parameter type does not match the specified type when the function is called, PHP generates a fatal error (Catchable fatal error ).
Class Name and array
When defining a function, PHP only supports two types of declarations: Class Name and array. Class Name table name the real parameters received by this parameter are the objects instantiated by the corresponding class. An array indicates that the received real parameters are of the array type. The following is an example:
Copy codeThe Code is as follows:
Function demo (array $ options ){
Var_dump ($ options );
}
When defining the demo () function, specify the parameter type received by the function as an array. If the input parameter is not of the array type when we call a function, such as the following call:
Copy codeThe Code is as follows:
$ Options = 'options ';
Demo ($ options );
The following error is returned:
Copy codeThe Code is as follows:
Catchable fatal error: Argument 1 passed to demo () must be of the type array, string given,
You can use null as the default parameter.
Note:
Note that PHP only supports two types of declarations, but does not support declarations of any other scalar types. For example, the following code produces an error:
Copy codeThe Code is as follows:
Function demo (string $ str ){
}
$ Str = "hello ";
Demo ($ str)
When we run the above Code, the string will be treated as the class name, so the following error will be reported:
Catchable fatal error: Argument 1 passed to demo () must be an instance of string, string given,
Summary
Type Declaration is also an improvement of PHP object-oriented, especially useful when capturing exceptions of a specified type.
Using the type declaration can also increase the readability of the Code.
However, because PHP is a weak language, the use of type declaration is contrary to the original intention of PHP design.
Whether to use or not to use the type declaration. You can see it, this cainiao does not :).