像javascript一樣動態為PHP對象增加方法

來源:互聯網
上載者:User
還在羨慕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教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.