Created
January 13, 2012 09:30
-
-
Save afoeder/1605272 to your computer and use it in GitHub Desktop.
Accessing private properties and methods using PHP's reflection
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class BareDemoClass() { | |
| protected $interestingThing = 42; | |
| } | |
| // during usual use, you'd have both the bare class and $instanciatedClass available | |
| $instanciatedClass = new BareDemoClass(); | |
| $reflectedProperty = new \ReflectionProperty('BareDemoClass', 'interestingThing'); | |
| $reflectedProperty->setAccessible(true); | |
| echo $reflectedProperty->getValue($instanciatedClass); | |
| // the idea is to have the property at first as "anonymous" property description without context; and with ->getValue you give the context: you pass in the desired object. | |
| ?> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.