Introduction to PHP Reflection API

Introduction to PHP Reflection API



1. What is Reflection API

reflection is the ability of a computer program to examine, introspect, and modify its own structure and behavior at runtime — wikipedia
/**
 * Class Profile
 */class Profile {
   /**
    * @return string
    */
   public function getUserName(): string
   {
      return 'Foo';
   }
}
// instantiation$reflectionClass = new ReflectionClass('Profile');

// get class name
var_dump($reflectionClass->getName());
=> output: string(7) "Profile"
// get class documentation
var_dump($reflectionClass->getDocComment());
=> output:
string(24) "/**
 * Class Profile
 */"
ReflectionClass: reports information about a class.
ReflectionFunction: reports information about a function.
ReflectionParameter: retrieves information about function’s or method’s parameters.
ReflectionClassConstant: reports information about a class constant.

2. Installation & Configuration:

3. Usage

// here we have the child class
class Child extends Profile {
}

$class = new ReflectionClass('Child');

// here we get the list of all parents
print_r($class->getParentClass()); // ['Profile']
$method = new ReflectionMethod('Profile', 'getUserName');
var_dump($method->getDocComment());
=> output:string(33) "/**
 * @return string
 */"
$class = new ReflectionClass('Profile');
$obj   = new Profile();
var_dump($class->isInstance($obj)); // bool(true)
// same like
var_dump(is_a($obj, 'Profile')); // bool(true)
// same like
var_dump($obj instanceof Profile); // bool(true)
// add getName() scope as privateprivate function getName(): string
{
    return 'Foo';
}
$method = new ReflectionMethod('Profile', 'getUserName');
// check if it is private so we set it as accessible
if ($method->isPrivate()) {
    $method->setAccessible(true);
}
echo $method->invoke(new Profile()); // Foo
  1. Documentation Generatorlaravel-apidoc-generator package, it is using ReflectionClass & ReflectionMethod extensively to get info about classes and methods doc blocks and then process them, checkout this block of code.
  2. Dependency Injection Container: will be introduced soon.

4. Conclusion

5. References

  1. http://php.net/manual/en/book.reflection.php

Comments

Popular posts from this blog

A Tailwind CSS Preset for Laravel 5.5

Short and safe array iteration

PHPStorm's performance