Detailed code examples for PHP reflection technology (GRAPHIC)

Source: Internet
Author: User

Summary

Compared to the reflection in Java, the reflection in PHP can really be a conscience. While Java is better than a maintenance perspective, it has the advantage. But the tedious processing also adds a certain amount of learning cost to the Java reflection mechanism.

Today, I try to use the reflection technology of PHP to get the information of the class.
The core operations can be found in the official PHP help document, which is most used here

Getpropertiesgetmethods

Target class

To better demonstrate the results of reflection and maintenance, create a class with the following directory structure:

<?phpclass person {private $name;    Private $age;    Private $address;        Public function __construct ($name, $age, $address) {$this->name = $name;        $this->age = $age;    $this->address = $address; The Public function setter ($key, $value) {exec ("{$this}->". $key.    "={$value}");     }/** * Wildcard method is not good.     * <br/> * Reason: Object person can is not a converted to string. * * @param unknown $key * @return String */Public Function getter ($key) {return exec (" $this ".    "->{$key}"); }/** * Simulates the Getter method implemented by the Java language.     <br/> * * Disadvantage: You need to provide a separate getter method for each private property, which makes the code slightly bloated.    */Public Function GetName () {return $this->name;    }}class Grade {private $name;    Public function __construct ($name) {$this->name = $name;    The Public Function SetName ($name) {$this->name = $name; } public Function GetName () {return $this->name; }}

Loading issues

Loading mechanism

Before the formal reflection operation, let's discuss the __autoload automatic loading mechanism. As the name implies, automated loading (classes, can also be other PHP files) chant.

For a deeper level, this involves how the PHP interpreter works. In other words, it is not possible for a project to write only one PHP file, instead, there may be hundreds of PHP files in a project, and it is unavoidable to call each other.

In other words, we declare and implement an addition function in a file, and we need to make a call in the B file. Obviously the addition is not implemented in the B file, so there is no way for the PHP interpreter to perform the addition operation.

This time you need to let the PHP interpreter know how to do this addition, so you need to require / include include the addition function of a file.

In this way, the PHP interpreter will know how to interpret and run our PHP files.

Similar to PHP, in the Java language we just need to add the statement before the source file import , the Java virtual machine can automatically in the relevant class information. And the strong type of Java can be found before compiling such problems, so the code maintenance is more convenient. PHP, however, needs to be done manually include/require .

But it should be clear that the two are just the same.

Automatic loading mechanism

However, if you manually load each PHP file to be referenced, you may want to write more than one of these load statements. Therefore, in order to deal with this problem conveniently, the automatic loading mechanism is introduced after PHP5.

void __autoload (String $class)

$classis the name of the class to be loaded, note the name.

How to use?

Since the automatic loading mechanism is so good, how do we use it?

The answer is to add a custom function to PHP that needs to load other class files __autoload($class) . Or just a file ab for example.

File A has a well-written class person, which you want to use in file B. Add a function to file B at this time __aotoload . And the way the function is written is relatively simple (everything is designed according to the simplest idea).

function __autoload ($class) {    $filename = "$class. class.php";        if (!file_exists ($filename)) {            throw new RuntimeException ("$filename file does not exist! ");    } else {        require "$filename";    }}

PHP interpreter in the scan to file B will be checked first, if the target class person is not introduced, it will be judged that there is no implementation __autoload , if there is the use of automatic loading function to load, otherwise error exits.

Attention issues

Although the above automatic loading function is relatively simple, but in reality it is necessary to pay a lot of "price", that is, the name of the loaded class file to be consistent with the class (no case-sensitive). Such as:

The name of the class to load is person, the name of the file where the class is located needs to be person.class.php, or Person.class.php

Moreover, the path problem is also a tricky problem, in this simple automatic loading function is not difficult to see, here they are located in the same class directory, imagine not satisfied with the condition of the situation, you can know how much the code of this automatic loading function will be.

In this case, it would also violate the original purpose of the automatic loading mechanism design. Therefore, it is necessary to store the relevant class files according to the specific directory structure.

The so-called: Added redundancy features, but brings the benefits of easy maintenance.

Personally, you may want to follow the Java language directory structure to maintain the PHP program, so there will be unexpected gains.

Reflection

The following formally enters the topic of reflection, which is already mentioned in the summary section. The focus is on ReflectionClass the use.

Reflection Properties

<?phprequire './bean/beans.php ';//person declares $protype = new Reflectionclass ("person") in the beans.php file;//You can add a parameter, To filter the operation. If only the properties of the public type are obtained $properties = $protype->getproperties ();//Reflection Gets the property information of the class foreach ($properties as $property) {    echo $property. " <br/> ";}

PHP is simpler than Java to get private properties.

Reflection method

<?phprequire './bean/beans.php '; $protype = new Reflectionclass ("person"), $methods = $protype->getmethods (); foreach ($methods as $method) {    echo $method->getname (). " <br/> ";}

In addition, you can add filter conditions. Give the GetMethods method a filter parameter.

Filter filters results to methods that contain only certain properties. The default is not filtered. Reflectionmethod::is_static, Reflectionmethod::is_public, reflectionmethod::is_protected, ReflectionMethod::IS_ Any combination of PRIVATE, reflectionmethod::is_abstract, reflectionmethod::is_final.

Reflection annotations

Note the information, which is the example of document information.

<?phprequire './bean/beans.php '; $protype = new Reflectionclass ("person"); $properties = $protype->getproperties ();//Reflection Gets the property information to the class foreach ($properties as $property) {    echo $property. ":";    $doc = $property->getdoccomment ();    echo "&nbsp;&nbsp;&nbsp;". $doc. "<br/>";    echo "--------------------------------------------------------". "<br/>";} $methods = $protype->getmethods (); foreach ($methods as $method) {    echo $method->getname (). " <br/> ";    $doc = $method->getdoccomment ();     echo "&nbsp;&nbsp;&nbsp;". $doc. "<br/>";     echo "--------------------------------------------------------". "<br/>";}

Reflection instantiation

Reflection Person Class

<?phprequire './bean/beans.php '; $protype = new Reflectionclass ("person");//The value obtained in the simulation database, thrown in the form of an associative array $values = Array (    "Name" = "Guo Pu",    "age", "    address" and "Dalian of Liaoning Province";//start instantiation $instance = $protype Newinstanceargs ($values);    Print_r ($instance);//Var_dump ($instance); Echo $instance->getname ();

Reflective Grade Class

<?phprequire './bean/beans.php '; $classprotype = new Reflectionclass ("Grade"); $class = $classprotype Newinstanceargs ("Name" = "Junior"); Var_dump ($class); Echo $class->getname ();

Methods for executing classes

$instance->getname (); Execute the method in person getname//or: $method = $class->getmethod (' getName '); Gets the GetName method in the Person class $method->invoke ($instance);    Execute the GetName method//or: $method = $class->getmethod (' setName '); Gets the SetName method in the Person class $method->invokeargs ($instance, Array (' snsgou.com '));

Summarize

In retrospect, this experiment demonstrates the reflection technology in PHP, and compares the implementation of the reflection technology in the Java language. Can only say that there are pros and cons of it.

In Java, reflection technology is the basis for writing a framework. Although the reflection technology in PHP is not particularly important, and the use of time constraints are more, slightly more chicken. But Bishi can still make some useful gadgets.

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.