原文地址: http://small.aiweimeng.top/index.php/archives/53.html
上一篇講到php能夠經過接口是實現代碼的複用。php
那麼這篇文章簡單介紹下使用_call實現代碼的複用。html
_call:php的一個魔術方法,當調用類中不存在的method時,會自動調用_call.this
示例代碼:htm
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,33blog