In strongly typed languages, type constraints are grammatical requirements, that is, when defining a variable, the type must be specified, and only that type of data can be stored in the future;
php is a weak type, which is characterized by the fact that it does not need to be The variable specifies the type, and any type can be stored thereafter. However, in PHP's new syntax, in some specific situations, syntax constraints can also be implemented for certain types.
that is You can set the type that must be used for the parameters of a function (method). Constraints can only be applied to objects, interfaces, arrays, and functions.
<code><span><span>function</span><span>f</span><span>(类名 <span>$p</span>)</span>{</span>} <span>// 要求参数只能使用该类的对象</span><span><span>function</span><span>f</span><span>(接口名 <span>$p</span>)</span>{</span>} <span>// 要求该参数只能使用实现该接口的对象</span><span><span>function</span><span>f</span><span>(arrary <span>$p</span>)</span>{</span>} <span>// 要求该参数只能使用数组</span><span><span>function</span><span>f</span><span>(callable <span>$p</span>)</span>// 要求该参数只能是一个函数(方法),此时称之为回调函数(方法)</span></code>
<code><span><span><?php</span><span><span>class</span><span>A</span>{</span>} <span><span>function</span><span>f</span><span>(A <span>$p</span>)</span>{</span>} <span>$obj</span> = <span>new</span> A(); f(<span>$obj</span>);</span></code>
The above has introduced the type constraints of PHP, including aspects of the content. I hope it will be helpful to friends who are interested in PHP tutorials.