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 -...