这篇文章简单介绍下使用_call实现代码的复用。
_call:php的一个魔术方法,当调用类中不存在的method时,会自动调用_call.
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | class One{ function method_1(){ echo '11<br/>'; } function method_2(){ echo '22<br/>'; } } class Two{ function method_3(){ echo '33<br/>'; } function method_4(){ echo '44<br/>'; } } class StaticDemo{ protected $Class = array(); public function __construct(array $class = array()){ $this->Class = $class; } public function __call($name, $arguments) { // TODO: Implement __call() method. foreach ($this->Class as $v){ if (is_callable(array($v, $name))) { //call_user_func_array在上篇文章中已作出理解 return call_user_func_array(array($v, $name), $arguments); } } return call_user_func_array(array($this, $name), $arguments); } } $obj = new StaticDemo(array(new One(), new Two())); $obj->method_1(); $obj->method_3(); |
运行结果:11,33