Home > Backend Development > PHP Tutorial > How is the Reflection reflection mechanism implemented in php?

How is the Reflection reflection mechanism implemented in php?

伊谢尔伦
Release: 2023-03-12 09:38:01
Original
1041 people have browsed it

This article mainly introducesExample introductionPHP’s Reflection reflection mechanism. This article introduces PHP’s Reflection reflection mechanism from the perspective of using Reflection to obtain information about a class. Friends who need it can refer to it

PHP5 adds a new feature: Reflection. This feature allows programmers to reverse-engineer class, interface, function, method and extension. Through PHP code, you can get all the information of an object and interact with it.
Suppose there is a class Person:

The code is as follows:

class Person {  
 /** 
     * For the sake of demonstration, we"re setting this private
     */ 
    private $_allowDynamicAttributes = false;
 
    /** type=primary_autoincrement */
    protected $id = 0;
 
    /** type=varchar length=255 null */
    protected $name;
 
    /** type=text null */
    protected $biography;
 
        public function getId()
        {
         return $this->id;
        }
        public function setId($v)
        {
            $this->id = $v;
        }
        public function getName()
        {
         return $this->name;
        }
        public function setName($v)
        {
          $this->name = $v;
        }
        public function getBiography()
        {
           return $this->biography;
        }
        public function setBiography($v)
        {
          $this->biography = $v;
        }
}
Copy after login

Through ReflectionClass, we can get the following information of the Person class:
1. Constants
2.Property Names
3.Method Names
4.Static PropertiesStatic Properties
5.Namespace Namespace
6.Whether the Person class is final or abstract

Just pass the class name "Person" to ReflectionClass:

The code is as follows:

$class = new ReflectionClass('Person');
Copy after login

Get the properties (Properties):

The code is as follows:

$properties = $class->getProperties();
foreach
($properties as $property) {
    echo $property->getName()."\n";
}
// 输出:
// _allowDynamicAttributes
// id
// name
// biography
Copy after login

By default, ReflectionClass will obtain all properties, including private and protected ones. If you only want to get the private attribute, you need to pass an additional parameter:

The code is as follows:

$private_properties = $class->getProperties(ReflectionProperty::IS_PRIVATE);
Copy after login

Available parameter list:

The code is as follows:

ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE
Copy after login

If you want to get both public and private properties, just write: ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED
It shouldn’t feel strange.

The property name can be obtained through $property->getName(), and the comment written to the property can be obtained through getDocComment.

The code is as follows:

foreach($properties as $property) {
    if($property->isProtected()) {
        $docblock = $property->getDocComment();
        preg_match('/ type\=([a-z_]*) /', $property->getDocComment(), $matches);
        echo $matches[1]."\n";
    }
}
// Output:
// primary_autoincrement
// varchar
// text
Copy after login

It’s a bit incredible. You can even get comments.
Get methods (methods): Get all methods of the class through getMethods(). What is returned is an array of ReflectionMethod objects. No more demonstrations.
Finally call the method in the class through ReflectionMethod.

The code is as follows:

$data = array("id" => 1, "name" => "Chris", "biography" => "I am am a PHP developer");
foreach($data as $key => $value) {
    if(!$class->hasProperty($key)) {
        throw new 
Exception
($key." is not a valid property");
    }
 
    if(!$class->hasMethod("get".
ucfirst
($key))) {
        throw new Exception($key." is missing a getter");
    }
 
    if(!$class->hasMethod("set".ucfirst($key))) {
        throw new Exception($key." is missing a setter");
    }
 
    // Make a new object to interact with
    $object = new Person();
 
    // Get the getter method and invoke it with the value in our data array
    $setter = $class->getMethod("set".ucfirst($key));
    $ok = $setter->invoke($object, $value);
 
    // Get the setter method and invoke it
    $setter = $class->getMethod("get".ucfirst($key));
    $objValue = $setter->invoke($object);
 
    // Now compare
    if($value == $objValue) {
        echo "Getter or Setter has modified the data.\n";
    } else {
        echo "Getter and Setter does not modify the data.\n";
   }
}
Copy after login

The above is the detailed content of How is the Reflection reflection mechanism implemented in php?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template