PHP 5.3中type hinting的用法

Posted on 2012-02-20 15:42 PHP博客 阅读(288) 评论(0)  编辑 收藏 引用 网摘
今天偶然看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){
&nbsp;&nbsp;&nbsp;&nbsp;print_r($arr);echo "<br/>";
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;
}
class Type_hint_new
{
&nbsp;&nbsp;&nbsp;&nbsp;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.

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//echo $obj->hint_method(); // Fatal Error: Argument must be an array
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo $obj->hint_method(array('P','H','P')); //First parameter must be an object of Type_hint class
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;function hint_null($obj = NULL) {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo "Allow NULL";
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
}

$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开关可以设置这个东西

只有注册用户登录后才能发表评论。
网站导航:

posts - 139, comments - 0, trackbacks - 0, articles - 0

Copyright © PHP博客