PHP 的__call()

来源:互联网 发布:知乎神经性耳鸣5年 编辑:程序博客网 时间:2024/04/30 02:40
PHP5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在或被权限控制中的方法,__call 方法将会被自动调用

例七:__call

[html] view plaincopy
  1. <?php  
  2. class foo {  
  3.   function __call($name,$arguments) {  
  4.     print("Did you call me? I'm $name!");  
  5.   }  
  6. } $x = new foo();  
  7. $x->doStuff();  
  8. $x->fancy_stuff();  
  9. ?>  



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

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

[html] view plaincopy
  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.   }   private function foo_for_int($x) {  
  9.     print("oh an int!");  
  10.   }   private function foo_for_string($x) {  
  11.     print("oh a string!");  
  12.   }  
  13. } $x = new Magic();  
  14. $x->foo(3);  
  15. $x->foo("3");  
  16. ?>  



引自:

_call___callStatic这两个函数是php类 的默认函数,

__call() 一个对象的上下文中,如果调用的方法不能访问,它将被触发

__callStatic() 一个静态的上下文中,如果调用的方法不能访问,它将被触发

实例:

[html] view plaincopy
  1. <?php  
  2. abstract class Obj  
  3. {  
  4. protected $property = array();  
  5.   
  6. abstract protected function show();  
  7.   
  8. public function __call($name,$value)  
  9. {  
  10. if(preg_match("/^set([a-z][a-z0-9]+)$/i",$name,$array))  
  11. {  
  12. $this->property[$array[1]] = $value[0];  
  13. return;  
  14. }  
  15. elseif(preg_match("/^get([a-z][a-z0-9]+)$/i",$name,$array))  
  16. {  
  17. return $this->property[$array[1]];  
  18. }  
  19. else  
  20. {  
  21. exit("<br>;Bad function name '$name' ");  
  22. }  
  23.   
  24. }  
  25. }  
  26.   
  27. class User extends Obj  
  28. {  
  29. public function show()  
  30. {  
  31. print ("Username: ".$this->property['Username']."<br>;");  
  32. //print ("Username: ".$this->getUsername()."<br>;");  
  33. print ("Sex: ".$this->property['Sex']."<br>;");  
  34. print ("Age: ".$this->property['Age']."<br>;");  
  35. }  
  36. }  
  37.   
  38. class Car extends Obj  
  39. {  
  40. public function show()  
  41. {  
  42. print ("Model: ".$this->property['Model']."<br>;");  
  43. print ("Sum: ".$this->property['Number'] * $this ->property['Price']."<br>;");  
  44. }  
  45. }  
  46.   
  47. $user = new User;  
  48. $user ->setUsername("Anny");  
  49. $user ->setSex("girl");  
  50. $user ->setAge(20);  
  51. $user ->show();  
  52.   
  53. print("<br>;<br>;");  
  54.   
  55. $car = new Car;  
  56. $car ->setModel("BW600");  
  57. $car ->setNumber(5);  
  58. $car ->setPrice(40000);  
  59. $car ->show();  
  60. ?>  

0 0
原创粉丝点击