Skip to content

Instantly share code, notes, and snippets.

@BrettBukowski
Created October 1, 2012 22:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrettBukowski/3814745 to your computer and use it in GitHub Desktop.
Save BrettBukowski/3814745 to your computer and use it in GitHub Desktop.
Quick reflection for PHP classes
/**
* 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