Created
October 1, 2012 22:03
-
-
Save BrettBukowski/3814745 to your computer and use it in GitHub Desktop.
Quick reflection for PHP classes
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
/** | |
* Provides quick reflection, usually so that the caller can access private | |
* methods and properies in a single pass. | |
* | |
* If called with a single String classname, then the \ReflectionClass of | |
* that class is returned. | |
* Accepts any number of additional Strings that are names of properties or | |
* methods to make accessible and return. Methods should be prefixed with 'method:'. | |
* The return value is an array containing the mapped reflection class and the properties / methods. | |
* | |
* Example: | |
* | |
* list($myClass, $someMethod, $privateVar) = reflect('\foo\bar\myClass', 'method:someMethod', 'privateVar') | |
* | |
* @return mixed Value | |
*/ | |
function reflect($className) { | |
$return = array(); | |
$substrIndex = strlen('method:'); | |
$class = new \ReflectionClass($className); | |
$return []= $class; | |
if (func_num_args() > 1) { | |
// Pop off the class name | |
$args = func_get_args(); | |
array_shift($args); | |
foreach ($args as $name) { | |
if (strpos($name, 'method:') === 0) { | |
$property = $class->getMethod(substr($name, $substrIndex)); | |
} | |
else { | |
$property = $class->getProperty($name); | |
} | |
$property->setAccessible(true); | |
$return []= $property; | |
} | |
} | |
if (count($return) === 1) { | |
return $class; | |
} | |
return $return; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment