This article mainly introduces the introduction of the type hinting function in PHP. This article explains the function of type hinting. Functions, usage methods and usage examples, friends in need can refer to it
Overview
Starting from PHP5, we can use type hints to specify the parameter types that the function receives when defining the function. If the parameter type is specified when defining a function, then when we call the function, if the type of the actual parameter does not match the specified type, PHP will generate a fatal error (Catchable fatal error).
Class name and array
When defining functions, PHP only supports two type declarations: class names and arrays. Class name table name The actual parameter received by this parameter is the object instantiated by the corresponding class, and the array indicates that the actual parameter received is an array type. Here is an example:
The code is as follows:
Function demo(array $options){
var_dump($options);
}
When defining the demo() function, the parameter type received by the function is specified as an array. If when we call a function, the parameter passed in is not an array type, such as a call like the following:
The code is as follows:
$options='options';
demo($options);
Then the following error will be generated:
The 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
Attention
One thing that needs special attention is that PHP only supports two types of type declarations. Any other scalar type declarations are not supported. For example, the following code will generate an error:
The code is as follows:
Function demo(string $str){
}
$str="hello";
demo($str)
When we run the above code, string will be treated as a 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 advancement in object-oriented PHP, especially when it comes to catching exceptions of a specified type.
Using type declarations can also increase the readability of code.
However, since PHP is a weakly typed language, using type declarations is contrary to the original intention of PHP design.
It’s up to everyone to have different opinions on whether to use type declarations or not. I’m a noob :).