Skip to content

Instantly share code, notes, and snippets.

@mrtimp
Created June 3, 2013 08:34
Show Gist options
  • Save mrtimp/5696880 to your computer and use it in GitHub Desktop.
Save mrtimp/5696880 to your computer and use it in GitHub Desktop.
Reflection helper for exposing a calling static and non static methods with (or without) arguments.
/**
* Reflection helper to expose a method as public (for unit testing)
* and call call the method with (or without) arguments. There is
* dynamic support for static methods
*
* <code>
*
* $r = new ReflectionHelper('MyClass', 'myMethod');
* $r->setPublic()->invoke("arg1", "arg2");
*
* </code>
*/
class ReflectionHelper {
/**
* @var string Store our class name for use when invoking the method
* @access private
*/
private $class;
/**
* @var \ReflectionMethod $method
* @access private
*/
private $method;
/**
* Create a reflection of a class method
*
* @param string $class The class we wish to reflect
* @param string $method The class method we wish to call
* @return \ReflectionHelper
* @access public
*/
public function __construct ($class, $method) {
$this->method = new ReflectionMethod($class, $method);
$this->class = $class;
return $method;
}
/**
* Set the called method to be publicly accessible
*
* @access public
*/
public function setPublic () {
$this->method->setAccessible(true);
return $this;
}
/**
* Call the method (with or without arguments)
*
* @access public
*/
public function invoke() {
$obj = ($this->method->isStatic() ? null : new $this->class);
$args = func_get_args();
if (!empty($args)) {
return $this->method->invokeArgs($obj, $args);
}
return $this->method->invoke($obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment