php 5.3中的一个type hinting的用法

今天偶然看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开关可以设置这个东西
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值