In computer science, reflection or reflection (holonim introspection, English reflection) means a process during which a program can monitor and modify its own structure and behavior at run time. - Wikipedia .What does the ability to stop and take a look inside your code ( reverse-engineering ) mean? Let's look at the following code snippet:
/** * Class Profile */ class Profile { /** * @return string */ public function getUserName(): string { return 'Foo'; } }
// $reflectionClass = new ReflectionClass('Profile'); // var_dump($reflectionClass->getName()); => output: string(7) "Profile" // var_dump($reflectionClass->getDocComment()); => output: string(24) "/** * Class Profile */"
ReflectionClass : reports class information.
ReflectionFunction : reports information about the function.
ReflectionParameter : retrieves information about the parameters of a function or method.
ReflectionClassConstant : reports information about a class constant.
// class Child extends Profile { } $class = new ReflectionClass('Child'); // print_r($class->getParentClass()); // ['Profile']
getUserName()
method documentation: $method = new ReflectionMethod('Profile', 'getUserName'); var_dump($method->getDocComment()); => output: string(33) "/** * @return string */"
instanceOf
and is_a()
for validating objects: $class = new ReflectionClass('Profile'); $obj = new Profile(); var_dump($class->isInstance($obj)); // bool(true) // var_dump(is_a($obj, 'Profile')); // bool(true) // var_dump($obj instanceof Profile); // bool(true)
// getName() private function getName(): string { return 'Foo'; } $method = new ReflectionMethod('Profile', 'getUserName'); // if ($method->isPrivate()) { $method->setAccessible(true); } echo $method->invoke(new Profile()); // Foo
- API Documentation Generator : The lavarel-apidoc-generator package makes extensive use of ReflectionClass and ReflrectionMethod to receive and subsequently process information about the documentation of the classes and methods, and design these blocks of code.
- Dependency Injection Container : check the whole topic here.
Source: https://habr.com/ru/post/433266/
All Articles