Home > Backend Development > PHP Tutorial > PHP type constraints

PHP type constraints

WBOY
Release: 2016-07-29 09:01:58
Original
1009 people have browsed it

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.

  • Specific occasions: formal parameter variables of functions (methods)
  • Specific types: object type (class name), interface type (interface name), array type (array), function type (callable)

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>
Copy after login
<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>
Copy after login
').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template