PHP Reflection mechanism to implement dynamic proxy code _ PHP Tutorial

Source: Internet
Author: User
PHP Reflection mechanism implements dynamic proxy code. The demo code is as follows :? PhpclassClassOne {functioncallClassOne () {printInClassOne ;}} classClassOneDelegator {private $ targets; function _ construct () {$ this-

The demo code is as follows:

Class ClassOne {
Function callClassOne (){
Print "In Class One ";
}
}
Class ClassOneDelegator {
Private $ targets;
Function _ construct (){
$ This-> target [] = new ClassOne ();
}
Function _ call ($ name, $ args ){
Foreach ($ this-> target as $ obj ){
$ R = new ReflectionClass ($ obj );
If ($ method = $ r-> getMethod ($ name )){
If ($ method-> isPublic ()&&! $ Method-> isAbstract ()){
Return $ method-> invoke ($ obj, $ args );
}
}
}
}
}
$ Obj = new ClassOneDelegator ();
$ Obj-> callClassOne ();
?>


Output result:
In Class One
It can be seen that the ClassOneDelegator class is used to replace the ClassOne class to implement its method.
Similarly, the following code can be run:

Class ClassOne {
Function callClassOne (){
Print "In Class One ";
}
}
Class ClassOneDelegator {
Private $ targets;
Function addObject ($ obj ){
$ This-> target [] = $ obj;
}
Function _ call ($ name, $ args ){
Foreach ($ this-> target as $ obj ){
$ R = new ReflectionClass ($ obj );
If ($ method = $ r-> getMethod ($ name )){
If ($ method-> isPublic ()&&! $ Method-> isAbstract ()){
Return $ method-> invoke ($ obj, $ args );
}
}
}
}
}
$ Obj = new ClassOneDelegator ();
$ Obj-> addObject (new ClassOne ());
$ Obj-> callClassOne ();
?>

Why :? Php class ClassOne {function callClassOne () {print "In Class One" ;}} class ClassOneDelegator {private $ targets; function _ construct () {$ this -...

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.