Skip to content

@afoeder /ReflectionDemo.php
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Accessing private properties and methods using PHP's reflection
<?php
/**
* 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');
$reflectedProperty->setAccessible(TRUE);
// 42
echo $reflectedProperty->getValue($instanciatedClass);
$reflectedMethod = new \ReflectionMethod('BareDemoClass', 'niceButPrivateMethod');
$reflectedMethod->setAccessible(TRUE);
// 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
Owner

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
Something went wrong with that request. Please try again.