Home > Backend Development > PHP Tutorial > Detailed explanation of php Reflection reflection mechanism example

Detailed explanation of php Reflection reflection mechanism example

伊谢尔伦
Release: 2023-03-12 09:18:02
Original
1498 people have browsed it

PHP5 adds a new feature: Reflection. This feature allows programmers to

reverse-engineer [reverse engineering] class, interface, function, method and extension [extension library support].

Through PHP code, you can get all the information of an object and interact with it.

Assume the following Person class:

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:

  • Constant Contents

  • Property Property Names

  • Method Names

  • Static PropertiesStatic Properties

  • Namespace Namespace

  • Whether the Person class is final or abstract

Just put the class name "Person" Just pass it to ReflectionClass:

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

* Get the properties (Properties):


##

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

By default, ReflectionClass will get To all attributes, private and protected are also available. If you only want to get the private attribute, you need to pass an additional parameter:


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

Available parameter list:

  • ReflectionProperty:: IS_STATIC

  • ReflectionProperty::IS_PUBLIC

  • ReflectionProperty::IS_PROTECTED

  • ReflectionProperty::IS_PRIVATE

If you want to get both public and private properties, just write like this: ReflectionProperty::IS_PUBLIC | ReflectionProperty::IS_PROTECTED

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


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 demonstration.

* Finally, call the method in the class through ReflectionMethod.


$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 Detailed explanation of php Reflection reflection mechanism example. 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