: This article mainly introduces how to dynamically add PHP Objects like javascript. if you are interested in PHP tutorials, refer to it. Are you still envious of how javascript can dynamically add methods to objects? is PHP also a solution? Next let's take a look!
The most important thing is that the dynamic expansion method also supports private attributes and methods inside the object to be accessed !!
/***Super method* 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 '); // you can access the private object and the protected method. oh $ o-> say_hello = function () {var_dump ($ this-> name); $ this-> haha () ;}; $ o-> say_hello ();
Easy to use !!
Author: xbs530 QQ: 987188548
PS: It's okay. you can exchange more technical information!
The above describes how to dynamically add PHP Objects like javascript, including some content, and hope to help those who are interested in PHP tutorials.