Skip to content

Instantly share code, notes, and snippets.

@Sergic
Forked from afoeder/ReflectionDemo.php
Created October 31, 2013 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sergic/7247276 to your computer and use it in GitHub Desktop.
Save Sergic/7247276 to your computer and use it in GitHub Desktop.
<?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