What is the principle of the PHP reflection mechanism? The Reflection mechanism action explanation

Source: Internet
Author: User
This article mainly introduced the PHP reflection mechanism principle and usage, combined with the example form analysis PHP reflection mechanism principle, the usage and the related attention matters, the need friend can refer to the next

This paper describes the principle and usage of PHP reflection mechanism. Share to everyone for your reference, as follows:

Reflection

Objects in object-oriented programming are given the ability to introspect, and the process of introspection is reflection.

Reflection, the intuitive understanding is to find the origin and source according to the arrival. For example, for a bare object, we can just use this object to know what class it belongs to and what methods it has.

Reflection refers to the extension of the parsing PHP program in PHP running state, exporting or presenting details about classes, methods, properties, parameters, etc., 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

<?phpclass person{public $name;p ublic $gender;p ublic function Say () {  echo $this->name, "\tis", $this- Gender, "\ r \ n";} Public function set ($name, $value) {  echo ' Setting $name to $value \ r \ n ';  $this $name = $value;} Public function Get ($name) {  if (!isset ($this, $name)) {    echo ' is not set ';     $this $name = "Setting defaults for You";  }  return $this $name;  }} $student =new person (); $student->name= ' Tom '; $student->gender= ' male '; $student->age=24;  

Now, what do you do to get the list of methods and properties for this student object? As shown in the following code:

Gets the object property list $reflect = new Reflectionobject ($student), $props = $reflect->getproperties (), and foreach ($props as $prop) { C0/>print $prop->getname (). " \ n ";} Gets the object method list $m= $reflect->getmethods (), foreach ($m as $prop) {  print $prop->getname (). \ n ";}

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

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

If this object is coming from another page, how do you know which class it belongs to? A code can be done:

Gets the class to which the object property list belongs echo Get_class ($student);

The capabilities of the reflection API are obviously more powerful, and even the prototypes of this class can be restored, including access to methods such as:

Reflection gets the prototype of the class $obj = new Reflectionclass (' person '), $className = $obj->getname (); $Methods = $Properties = Array (); foreach ($obj->getproperties () as $v) {$Properties [$v->getname ()] = $v;} foreach ($obj->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";

The output is as follows:

Class person{public  Gender public  name  function get () {}  function set () {}  function say () {}}

Not only that, there are dozens of more about the reflection API 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 a class, is it possible to use it as a hook to implement plug-in functionality? Or is it a dynamic agent?

For example:

<?phpclass MySQL {  function connect ($db) {    echo "connected to Database ${db[0]}\r\n";  }} Class Sqlproxy {  private $target;    function construct ($tar) {     $this->target[] = new $tar ();  }  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 before intercept record log\r\n";          $method->invoke ($obj, $args);          echo "method to intercept \ r \ n";}}}}  $obj = new Sqlproxy (' MySQL '); $obj->connect (' member ');

In the normal development, there are not many places to use 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 consumption of reflection 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.

Related Article

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.