PHP5学习笔记:用__call()实现方法重载

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

 

复制代码
<?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"); ?>
相关文章
相关标签/搜索