Add methods to PHP objects dynamically like JavaScript

Source: Internet
Author: User
Still envy JavaScript can dynamically add methods to the object, PHP is also a way to yo? Then look down!

The most important thing is that the dynamic extension method also supports accessing the object's internal private properties and methods Oh!!

  /** * Super Method* Class Supermethod */classsupermethod{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;returnCall_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($valueinstanceofClosure) {$this -_bind_function_map[$name]=$value -BindTo($this);}    }function__get($name)    {if($this -_friend_call_in_progress){return$this -$name;}    }}classTestextendssupermethod{protected$name='';Public function__construct($name='')    {$this -name=$name;}protected functionhaha(){phpinfo ();}}$o=NewTest (' Xbs ');//It has access to object-private and protected methods .$o -Say_hello=function(){Var_dump ($this -name);$this -haha();};$o -Say_hello();

How to use simple it!!

Author: xbs530 qq:987188548

PS: Nothing can be a lot of communication technology Oh!

The above describes the same as JavaScript dynamic additions to the PHP object, including aspects of the content, I hope the PHP tutorial interested in a friend helpful.

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    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.