Home  >  Article  >  Backend Development  >  PHP reflection dynamic proxy

PHP reflection dynamic proxy

藏色散人
藏色散人forward
2019-09-23 09:14:093607browse

Reflection can detect the internal structure of a class and can be used as a hook to implement plug-in functions or as a dynamic proxy.

Reflection-related

Functions related to classes and objects

get_object_vars
get_class_methods
get_class_vars
get_class
get_parent_class
method_exists
property_exists
trait_exists

Reflection-related API classes

reflectiontype
reflectionproperty
reflectionobject
reflectionfunction
reflectionmethod
reflectionexception
reflectionextension
reflectionparameter
reflectionfunctionabstract
reflectiongenerator
reflectionclass
reflectionclassconstant
reflectionzendextension

Reflection The API is more powerful and can even restore the prototype of this class, including method access permissions, etc.

Application scenarios

One is to debug the object, and the other is to obtain Class information usually has the following application methods

Document generation uses it to scan the classes in the file and generate description documents

Plug-in development In MVC and plug-in development, reflection is commonly used

Disadvantages

The performance consumption of reflection is also very large. Under normal circumstances, try not to use

, which will destroy the encapsulation of the class, because reflection can make things that are not The methods or properties that should be exposed are forced to be exposed

Example

The following is a simple database dynamic proxy implemented using the reflection feature

Based on dynamic proxy, there is more room for imagination, such as implementing interceptors, adding attribute methods, cropping, etc.

class Mysql
{
    function connect($db){
         echo "connecting database ${db[0]}\r\n";
    }
}
class SqlProxy
{
    private $target;
     function __construct($tar){
         $this->target[]  = new $tar();
     }
     function __call($name, $args){
             if($method = $r->getMethod($name)){
                 if($method->isPublic() && !$method->isAbstract()){
                     echo "method before record \r\n";
                     $method->invoke($obj,$args);
                     echo "method after record\r\n";
                 }
             }
         }
     }
 }
 $obj = new SqlProxy('Mysql');
 $obj->connect('member');

Others

echo and print are both languages structure, but the latter has a return value

print_r and var_dump are ordinary functions that can print multiple types of data, but the latter will output the data type, and the second parameter of the former can change the output to return

Recommendation: "PHP Tutorial"

The above is the detailed content of PHP reflection dynamic proxy. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete