今天在网上发现了一片好文章,介绍_call()方法。
依靠这个方法可以实现方法重载,这是找了好久的东西了。
发在这里,算作笔记。
---------------------------------------
PHP5 的对象新增了一个专用方法 __call(),这个方法用来监视一个对象中的其它方法。如果你试着调用一个对象中不存在的方法,__call 方法将会被自动调用。

例七:__call
<?php
class foo {
  function __call($name,$arguments) {
    print("Did you call me? I'm $name!");
  }
$x = new foo();
$x->doStuff();
$x->fancy_stuff();
?>



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

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

 

<?php
class Magic {
  function __call($name,$arguments) {
    if($name=='foo') {
        if(is_int($arguments[0])) $this->foo_for_int($arguments[0]);
        if(is_string($arguments[0])) $this->foo_for_string($arguments[0]);
    }
  } 
  private function foo_for_int($x) {
        print("oh an int!");
  }  
  private function foo_for_string($x) {
        print("oh a string!");
  }

$x = new Magic();
$x->foo(3);
$x->foo("3");
?>


 

posted on 2011-09-22 13:57  小炒花生米  阅读(4384)  评论(0编辑  收藏  举报