public
Last active

Accessing private properties and methods using PHP's reflection

  • Download Gist
ReflectionDemo.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
<?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');
?>

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.