__call、__set 和 __get的用法

来源:互联网 发布:java调用sql存储过程 编辑:程序博客网 时间:2024/05/22 13:07

__call、__set 和 __get的用法

    博客分类: 
  • Php / Mysql
PHP

__call的用法

 

PHP5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在的方法,__call 方法将会被自动调用。

 

例:__call

 

Php代码  收藏代码
  1. <?php  
  2. class foo {  
  3.     function __call($name,$arguments) {  
  4.         print("Did you call me? I'm $name!<br>");  
  5.         print_r($arguments);  
  6.         print("<br><br>");  
  7.     }  
  8.   
  9.     function doSecond($arguments)  
  10.     {  
  11.         print("Right, $arguments!<br>");  
  12.     }  
  13. }   
  14.    
  15. $test = new foo();  
  16. $test->doFirst('no this function');  
  17. $test->doSecond('this function exist');  
  18. ?>  
 

 

__call 实现“过载”动作

 

 这个特殊的方法可以被用来实现“过载(overloading)”的动作,这样你就可以检查你的参数并且通过调用一个私有的方法来传递参数。

 

例:使用 __call 实现“过载”动作

 

Php代码  收藏代码
  1. <?php  
  2. class Magic {  
  3.     function __call($name,$arguments) {  
  4.         if($name=='foo') {  
  5.             if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);  
  6.             if(is_string($arguments[0])) $this->foo_for_string($arguments[0]);  
  7.         }  
  8.     }     
  9.       
  10.     private function foo_for_int($x) {  
  11.         print("oh an int!");  
  12.     }     
  13.           
  14.     private function foo_for_string($x) {  
  15.         print("oh a string!");  
  16.     }  
  17. }   
  18.   
  19. $test = new Magic();  
  20. $test->foo(3);  
  21. $test->foo("3");  
  22. ?>  
 

 

 __set 和 __get的用法

 

这是一个很棒的方法,__set 和 __get 方法可以用来捕获一个对象中不存在的变量和方法。

 

例: __set 和 __get

 

Php代码  收藏代码
  1. <?php  
  2. class foo {  
  3.     function __set($name,$val) {  
  4.         print("Hello, you tried to put $val in $name<br>");  
  5.     }  
  6.    
  7.     function __get($name) {  
  8.         print("Hey you asked for $name<br>");  
  9.     }  
  10. }  
  11.   
  12. $test = new foo();  
  13. $test->__set('name','justcoding');  
  14. $test->__get('name');  
  15. ?>