免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1871 | 回复: 1
打印 上一主题 下一主题

php 5.3中的一个type hinting的用法 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-01-20 20:46 |只看该作者 |倒序浏览

php 5.3中的一个type hinting的用法







今天偶然看php 5.3中的一个特性,叫type hinting(类型提示?),感觉怪怪的,看了下,
大概如下,比如有个类:
  1. class Customer {
  2. ...
  3. }

  4. class Order {
  5.    public function myfunc($c)
  6.    {
  7. ...
  8.    }
  9. }

  10. $o = new Order();
  11. $o->myfunc(xxxxx);
复制代码
如果myfunc中没规定参数的类型,则可以传不同类型的参数进去,为了规范,假设要传入的是只能customer类的实例,可以这样:
  1. class Customer {
  2. ...
  3. }

  4. class Order {
  5.    public function myfunc(Customer $c)
  6.    {
  7. ...
  8.    }
  9. }
复制代码
现在myfunc只能接收Customer类的实例,如果传进去的不是,则报FATAL错了

再看一个例子:



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

论坛徽章:
0
2 [报告]
发表于 2012-01-20 20:46 |只看该作者
谢谢分享
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP