Skip to content

Instantly share code, notes, and snippets.

@afoeder
Created January 13, 2012 09:30
Show Gist options
  • Save afoeder/1605272 to your computer and use it in GitHub Desktop.
Save afoeder/1605272 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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