今天在网上发现了一片好文章,介绍_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");
?>


 

相关文章:

  • 2022-12-23
  • 2021-05-24
  • 2022-12-23
  • 2021-04-01
  • 2021-07-27
  • 2021-08-30
  • 2021-05-22
猜你喜欢
  • 2022-12-23
  • 2021-09-21
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案