Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get the value of a private property with Reflection?

Tags:

php

reflection

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?

like image 869
Alex Avatar asked Jul 22 '12 23:07

Alex


People also ask

What is PHP reflection?

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.

What is C# reflection?

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.

Can properties be private?

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.


2 Answers

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)); 
like image 139
zerkms Avatar answered Sep 16 '22 19:09

zerkms


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.

like image 29
Vasiliy Avatar answered Sep 19 '22 19:09

Vasiliy