Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Accessing private properties and methods using PHP's reflection
* Please be aware that private properties are private for good purpose,
* changing it during runtime so is only OK during Unit Testing for example.
* So use this only if you're knowing what you're doing :)
class BareDemoClass() {
protected $interestingThing = 42;
protected function niceButPrivateMethod() {
return "DNA N47°16' E11°23'";
// during usual use, you'd have both the bare class and $instanciatedClass available
$instanciatedClass = new BareDemoClass();
$reflectedProperty = new \ReflectionProperty('BareDemoClass', 'interestingThing');
// 42
echo $reflectedProperty->getValue($instanciatedClass);
$reflectedMethod = new \ReflectionMethod('BareDemoClass', 'niceButPrivateMethod');
// DNA N47°16' E11°23'
echo $reflectedMethod->invoke($instanciatedClass);
// you could also get the reflected property or method using the object itself:
$reflectedObject = new \ReflectionObject($instanciatedClass);
$reflectedProperty = $reflectedObject->getProperty('interestingThing');
// continue like above; or
$reflectedMethod = $reflectedObject->getMethod('niceButPrivateMethod');

afoeder commented Jan 13, 2012

passing the instanciated class as parameter of ->getValue() or ->invoke() seems a bit weird because it doesn't match the reading style you may be used to; but consider it giving the Reflection the correct context.
Just regard the reflected methods and properties at first being "anonymous" and not bound to a specific object, but only class. Getting a value requires that object context, and with the passed parameter you give it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment