PHP is a weak type. Its characteristic is that there is no need to specify a type for the variable, and any type can be stored afterwards. However, in the new syntax of php, in some specific occasions, for some For specific types, syntactic constraints can also be performed.
Specific occasions: formal parameter variables of functions (methods)
Specific types: Object type (class name), Interface type (interface name) ), arraytype (array), function type (callable)
function f(类名 $p){} // 要求参数只能使用该类的对象 function f(接口名 $p){} // 要求该参数只能使用实现该接口的对象 function f(arrary $p){} // 要求该参数只能使用数组 function f(callable $p) // 要求该参数只能是一个函数(方法),此时称之为回调函数(方法)
<?php class A{} function f(A $p){} $obj = new A(); f($obj);
The above is the detailed content of PHP type constraint usage example_php tips. For more information, please follow other related articles on the PHP Chinese website!