六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 141|回复: 0

php 5.3中的一个type hinting的用法

[复制链接]

升级  73.25%

801

主题

801

主题

801

主题

探花

Rank: 6Rank: 6

积分
2465
 楼主| 发表于 2013-2-7 01:49:19 | 显示全部楼层 |阅读模式
今天偶然看php 5.3中的一个特性,叫type hinting(类型提示?),感觉怪怪的,看了下,
大概如下,比如有个类:

class Customer {
...
}

class Order {
   public function myfunc($c)
   {
...
   }
}

$o = new Order();
$o->myfunc(xxxxx);

如果myfunc中没规定参数的类型,则可以传不同类型的参数进去,为了规范,假设要传入的是只能customer类的实例,可以这样:
class Customer {
...
}

class Order {
   public function myfunc(Customer $c)
   {
...
   }
}
  现在myfunc只能接收Customer类的实例,如果传进去的不是,则报FATAL错了

再看一个例子:
class Type_hint{     function hint_method(array $arr){    print_r($arr);echo "<br/>";    }     }class Type_hint_new{    function hint_object(Type_hint $obj){  // Here, If I didn’t pass in an Type_hint object to hint_object(), a FATAL_ERROR was occured.        //echo $obj->hint_method(); // Fatal Error: Argument must be an array        echo $obj->hint_method(array('P','H','P')); //First parameter must be an object of Type_hint class    }     function hint_null($obj = NULL) {            echo "Allow NULL";        }}$obj=new type_hint();$obj_new = new Type_hint_new();$obj->hint_method(array('b','h','u','m','i'));$obj_new->hint_object($obj);  $obj_new->hint_null(NULL);


输出:
Array ( [0] => b [1] => h [2] => u [3] => m [4] => i )
Array ( [0] => P [1] => H [2] => P )
Allow NULL

而E_RECOVERABLE_ERROR 这个PHP.INI开关可以设置这个东西
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表