Skip to content

Instantly share code, notes, and snippets.

@johnhalsey
Created April 8, 2019 14:52
Show Gist options
  • Save johnhalsey/c52e6dc28f56cd01e35110577a3aa4f1 to your computer and use it in GitHub Desktop.
Save johnhalsey/c52e6dc28f56cd01e35110577a3aa4f1 to your computer and use it in GitHub Desktop.
Call a PHP private or protected method (good for tests)
/**
* Call protected/private method of a class.
*
* @param object &$object Instantiated object that we will run method on.
* @param string $methodName Method name to call
* @param array $parameters Array of parameters to pass into method.
*
* @return mixed Method return.
* @throws \ReflectionException
*/
public function invokeMethod(&$object, $methodName, array $parameters = array())
{
$reflection = new \ReflectionClass(get_class($object));
$method = $reflection->getMethod($methodName);
$method->setAccessible(true);
return $method->invokeArgs($object, $parameters);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment