It doesn't seem to work:
$ref = new ReflectionObject($obj); if($ref->hasProperty('privateProperty')){ print_r($ref->getProperty('privateProperty')); }
It gets into the IF loop, and then throws an error:
Property privateProperty does not exist
:|
$ref = new ReflectionProperty($obj, 'privateProperty')
doesn't work either...
The documentation page lists a few constants, including IS_PRIVATE
. How can I ever use that if I can't access a private property lol?
The term “reflection” in software development means that a program knows its own structure at runtime and can also modify it. This capability is also referred to as “introspection”. In the PHP area, reflection is used to ensure type safety in the program code.
Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.
class A { private $b = 'c'; } $obj = new A(); $r = new ReflectionObject($obj); $p = $r->getProperty('b'); $p->setAccessible(true); // <--- you set the property to public before you read the value var_dump($p->getValue($obj));
Please, note that accepted answer will not work if you need to get the value of a private property which comes from a parent class.
For this you can rely on getParentClass method of Reflection API.
Also, this is already solved in this micro-library.
More details in this blog post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With