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错了
再看一个例子:
Java代码- 1.class Type_hint{
- 2. function hint_method(array $arr){
- 3. print_r($arr);echo "<br/>";
- 4. }
- 5.
- 6.}
- 7.class Type_hint_new
- 8.{
- 9. 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.
- 10.
- 11. //echo $obj->hint_method(); // Fatal Error: Argument must be an array
- 12. echo $obj->hint_method(array('P','H','P')); //First parameter must be an object of Type_hint class
- 13. }
- 14. function hint_null($obj = NULL) {
- 15. echo "Allow NULL";
- 16. }
- 17.}
- 18.
- 19.$obj=new type_hint();
- 20.$obj_new = new Type_hint_new();
- 21.$obj->hint_method(array('b','h','u','m','i'));
- 22.$obj_new->hint_object($obj);
- 23.$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开关可以设置这个东西
|