Home > Backend Development > PHP Tutorial > PHP参数类型限制

PHP参数类型限制

WBOY
Release: 2016-06-23 13:09:43
Original
1571 people have browsed it

PHP如同其他语言(OC,Java),也引入了参数类型的检查,不过,PHP只有数组和对象两种限定类型,诸如string、integer这样的限定类型是没有的。参数类型限制,这个不论是接口,抽象类,函数,方法,在5.3+以上版本都可以使用,不过目前只能声明 array object 这两种.

这样做的好处:

①:可以协调编码,至少我不用看注释或代码,就知道该传个怎样的参数进去。

②:对传入的对象使用类型声明,可不需要在函数内使用 is_a 函数鉴别传入对象是否合法而把甄别工作交予编译器完成

is_a --  如果对象属于该类或该类是此对象的父类则返回 TRUE 

class User{     public $name;     public $password;     function __construct($name,$password){         $this->name=$name;         $this->password=$password;     } }//参数可以指定对象类型function f1(User $user){     echo $user->name,”,”,$user->password; }//参数可以指定数组类型function f2(array $arr){}//参数不可以指定基本类型,下面一句会出错function f3(string $s){}
Copy after login


好的,接下来进行验证:

当给f1()函数传入字符串时,会报错:

$a = 'xiaojun';

$ret = f1($a);

错误:

PHP Catchable fatal error: Argument 1 passed to f1() must be an instance of User, string given, called in /tmp/f921205b-ef87-4aa8-b715-a131af661abd/code on line 16 and defined in /tmp/f921205b-ef87-4aa8-b715-a131af661abd/code on line 11

错误描述的很清楚,必须给函数传递一个User的实例化对象。

这样才是正确的:

// 实例化对象,并初始化$user_obj = new User("kaiyi", '123456');$ret = f1($user_obj);
Copy after login



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