What is reflection in PHP? Reflection usage Examples

Source: Internet
Author: User
Objects in object-oriented editing are given the ability to introspect, and the process of introspection is reflection.

Reflective, intuitive understanding the origin and source are identified according to the arrival. Let's say I give you a bare object, and I can just use this object to know what class it belongs to and what methods it has.

Reflection refers to the PHP running state, extending the parsing PHP program, exporting or extracting details about classes, methods, properties, parameters, including comments. This dynamic acquisition of information and the ability to dynamically invoke object methods are called Reflection APIs

How to use the Reflection API

Take the following code as an example

Class handsonboy{public    $name = ' Chenqionghe ';    Public $age =;    Public function set ($name, $value)    {        echo ' You are setting private properties '. $name. ' <br > value for '. $value. ' <br> ';        $this $name = $value;    }    Public function Get ($name)    {        if (!isset ($this, $name))        {            echo ' is not set '. $name;            $this, $name = "Setting default values for you". <br> ';        }        return $this $name;    }} $boy = new Handsonboy (); Echo $boy->name. ' <br/> '; $boy->hair = ' short ';

Now, what do you do to get the list of methods and properties for this student object? can be implemented with reflection, the code is as follows

$reflect = new Reflectionobject ($boy), $props = $reflect->getproperties ();//Gets the name of the property foreach ($props as $prop) {    Print $prop->getname (). Php_eol;} Gets the object method list $methos = $reflect->getmethods (); foreach ($methos as $method) {    print $method->getname (). Php_eol;}

You can also use the class function to return an associative array of object properties and more information without using the Reflection API: (for exposed properties and):

Returns an associative array of object Properties Var_dump (Get_object_vars ($boy));//Class attribute Var_dump (Get_class_vars (Get_class ($boy)));// Returns an array of method names consisting of the properties of the class Var_dump (Get_class_methods (Get_class ($boy)));

The capabilities of the reflection API are obviously more powerful, and even the prototype of this class can be restored, including access to the method, which simply encapsulates the code of a printing class

/** * @param $classObject object or class name */function getclass ($classObject) {$object = new R    Eflectionclass ($classObject);    $className = $object->getname ();    $Methods = $Properties = Array ();    foreach ($object->getproperties () as $v) {$Properties [$v->getname ()] = $v;    } foreach ($object->getmethods () as $v) {$Methods [$v->getname ()] = $v;    } echo "Class {$className}\n{\n";    Is_array ($Properties) && ksort ($Properties);        foreach ($Properties as $k = + $v) {echo "\ T"; echo $v->ispublic ()? ' Public ': ', $v->isprivate ()? ' Private ': ', $v->isprotected ()?        ' Protected ': '; $v->isstatic ()?        ' Static ': ';    echo "\t{$k}\n";    } echo "\ n";    if (Is_array ($Methods)) Ksort ($Methods);    foreach ($Methods as $k = + $v) {echo "\tfunction {$k} () \ n"; } echo "}\n";} 

Not only that, there are dozens of of the reflection APIs in the PHP manual, so to speak, reflection completely describes a prototype of a class or object. Reflection can be used not only for classes and objects, but also for functions, extension modules, exceptions, and so on.

What is the effect of reflection?

Reflection can be used for document generation, so you can use it to scan the classes in a file, generating a description document one by one.

Since reflection can detect the internal structure of the class, can it be used as a hook to implement plug-in functions? or is it a dynamic agent? The following code is a simple example.

<?phpclass mysql{    function Connect ($db)    {        echo "connected to database {$db [0]}". Php_eol;}    } Class sqlproxy{    private $target;    Public function construct ($tar)    {        $this->target[] = new $tar;    }    Public function call ($name, $args)    {        foreach ($this->target as $obj)        {            $r = new Reflectionclass ( $obj);            if ($method = $r->getmethod ($name))            {                if ($method->ispublic () &&! $method->isabstract ())                {                    echo "method to intercept log before". Php_eol;                    $method->invoke ($obj, $args);                    echo "method after intercept". Php_eol;}}}}    $obj = new Sqlproxy (' MySQL '); $obj->connect (' Chenqionghe ');

The real operation class here is the MySQL class, but Sqlproxy implements the actual class run based on the dynamically passed in parameters, and intercepts the method before and after it runs, and dynamically alters the methods and properties in the class. This is the simple dynamic proxy.

There is not much use in the usual development of reflection: one is to debug the object, and the other is to get the information of the class. In MVC and plug-in development, the use of reflection is very common, but the reflection consumption is also very large, in case you can find alternatives, do not misuse.

PHP has the token function, which can be used to implement some reflection functions. From a simple and flexible point of view, it is advisable to use the reflection API that has been provided.

Many times, the use of reflection can keep the code elegant and concise, but reflection also destroys the encapsulation of the class, because reflection can make a method or property that should not be exposed is forced to expose, which is both an advantage and a disadvantage.

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.