Skip to content

Instantly share code, notes, and snippets.

@coyl
Created May 16, 2016 19:35
Show Gist options
  • Save coyl/7f4df52b49f1f7149bfaa724c0cb6c29 to your computer and use it in GitHub Desktop.
Save coyl/7f4df52b49f1f7149bfaa724c0cb6c29 to your computer and use it in GitHub Desktop.
How to test protected methods
/**
* Invoke protected or private method of object
*
* @param object $object
* @param string $method name of method to invoke
* @param mixed $arg1 args that passed to invoked method [optional]
*
* @return mixed
*
* @throws \Exception
*/
public static function callProtectedMethod($object, $method, $arg1 = null)
{
$args = array_slice(func_get_args(), 2);
$reflectionMethod = new \ReflectionMethod(get_class($object), $method);
if ($reflectionMethod->isPublic()) {
throw new \Exception(sprintf('%s::%s already accessible', get_class($object), $method));
}
$reflectionMethod->setAccessible(true);
$result = $reflectionMethod->invokeArgs($object, $args);
$reflectionMethod->setAccessible(false);
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment