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
- Documentation Generator: laravel-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.
- Dependency Injection Container: will be introduced soon.
4. Conclusion
PHP is providing a rich Reflection API that makes life easy to reach any area of the OOP structures.

Comments
Post a Comment