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 ( => b => h => u => m => i )
Array ( => P => H => P )
Allow NULL
而E_RECOVERABLE_ERROR 这个PHP.INI开关可以设置这个东西
页:
[1]