-
-
Save Sergic/7247276 to your computer and use it in GitHub Desktop.
This file contains 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 | |
/** | |
* 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'); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment