Home > Backend Development > PHP Tutorial > PHP type constraint usage example_php tips

PHP type constraint usage example_php tips

怪我咯
Release: 2023-03-13 22:34:01
Original
1479 people have browsed it

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)
// 要求该参数只能是一个函数(方法),此时称之为回调函数(方法)
Copy after login
<?php
class A{}
function f(A $p){}
$obj = new A();
f($obj);
Copy after login

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!

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