Introducing Reflection reflection mechanism of PHP with examples

  • 2021-07-10 19:11:25
  • OfStack

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


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;
        }
}

With ReflectionClass, we can get the following information about the Person class:
1. Constant Contants
2. Attribute Property Names
3. Method Method Names
4. Static Attribute Static Properties
5. Namespace Namespace
6. Is the Person class final or abstract

Just pass the class name "Person" to ReflectionClass:


$class = new ReflectionClass('Person');

Gets the property (Properties):


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

By default, ReflectionClass gets all the properties, as do private and protected. If you only want to get the private attribute, you have to pass an extra parameter:


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

List of available parameters:


ReflectionProperty::IS_STATIC
ReflectionProperty::IS_PUBLIC
ReflectionProperty::IS_PROTECTED
ReflectionProperty::IS_PRIVATE

If you want to get both public and private attributes, write: ReflectionProperty:: IS_PUBLIC ReflectionProperty:: IS_PROTECTED
It shouldn't feel strange.

Through $property- > getName () can get the attribute name, and getDocComment can get the annotation written to property.


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

It's a little incredible. Even the annotations can be obtained.
Get method (methods): Get all methods of the class through getMethods (). Returns an array of ReflectionMethod objects. No more demos.
Finally, call 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";
   }
}

Isn't it interesting?


Related articles: