Why RreflectionClass?

Don't really understand the purpose and practical applications of this thing php.net/manual/ru/class.reflectionclass.php despite the fact that you can:
class My {
 function __construct($arr) {
var_dump($arr);
}
}

$class = 'My';
$a = new $class([1,2]);
June 8th 19 at 17:00
4 answers
June 8th 19 at 17:02
Solution
Another good example of the use ReflectionClass - Dependency Resolution in the Laravel container.
I recently just Dayle Rees interesting stuff published on this topic.

I personally use in my abstract class for WordPress plugins, it allows you to make tight the implementation with the abstract in the opposite direction (in WP this is sometimes necessary, especially in large projects).

When writing any performance-analyzer and debug, Reflection* allows you to gather Stack Traces and other useful info.

In General, in some cases, irreplaceable piece. But not every day.
June 8th 19 at 17:04
Solution
Though rare, but necessary sometimes. The example I remember: it was necessary to forbid developers to add in class (and his successors) constants without the prefix "SOME_PREFIX_". We write a unit test, which through reflexes gets a list of all constants of a class and verifies their names. The result is constant with the wrong name not passed the test, and forced the developer to rewrite your code.

In tests it is sometimes necessary to temporarily make private property public, then again comes to the aid of ReflectionClass:
$obj = new TestableClass();
$reflection = new ReflectionClass($obj);

$privatProperty = $reflection->getProperty('privateProperty');
$privatProperty->setAccessible(true);
$privatProperty->setValue($obj, 'value');


Things like PHP CodeSniffer also use reflexes. Another example is phpdoc. As soon as a problem arises of generating code from phpdoc comments, no reflexes here anywhere (except to invent a Bicycle for parsing).
June 8th 19 at 17:06
Solution
An example of practical use ReflactionClass: https://github.com/baryshev/Annotator/blob/master/...
June 8th 19 at 17:08
Solution
always use. here, 4 hours ago wrote a wonderful test for the presence of properties in an object:

foreach ($validatorAttrs as $validator_property_key => $validator_property_value) {
 // Check the class of such properties.
 try {
$reflection->getProperty($validator_property_key);
 } catch (\ReflectionException $e) {
 throw new \InvalidArgumentException(
 get_class($this) . ": Bad call validator settings on property `$key`: ". $e->getMessage()
);
}
 // Set properties validator specified by the customer.
 $o->$validator_property_key = $validator_property_value;
}

Find more questions by tags PHP