還在羨慕javascript可以動態為對象增加方法嗎,PHP也是有辦法的喲?接著往下看吧!
最為重要的是動態擴充的方法也是支援訪問對象內部私人屬性和方法噢!!
/** * 超級方法* Class SuperMethod */class SuperMethod{private $_bind_function_map=array();private $_friend_call_in_progress=0;function __call($name, $arguments) {if(isset($this->_bind_function_map[$name])){$this->_friend_call_in_progress++;try{$res=call_user_func_array($this->_bind_function_map[$name],$arguments);$this->_friend_call_in_progress--;}catch (\Exception $e){$this->_friend_call_in_progress--;throw $e;}return $res;}else{if($this->_friend_call_in_progress){$arguments['_friend_call']=$name;return call_user_func($this,$arguments);} } }function __invoke($args) {if(isset($args['_friend_call'])){$friend_call=$args['_friend_call'];unset($args['_friend_call']);return $this->$friend_call(...$args);} }function __set($name, $value) {if($value instanceof Closure){$this->_bind_function_map[$name]=$value->bindTo($this);} }function __get($name) {if($this->_friend_call_in_progress){return $this->$name;} }}class test extends SuperMethod{protected $name='';public function __construct($name='') {$this->name=$name;}protected function haha(){ phpinfo();}}$o=new test('xbs');//裡面可以訪問對象私人以及受保護方法噢$o->say_hello=function(){ var_dump($this->name);$this->haha();};$o->say_hello();
怎麼樣使用簡單吧!!
作者:xbs530 QQ:987188548
PS:沒事可以多多交流技術噢!
以上就介紹了像javascript一樣動態為PHP對象增加方法,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。