Created
May 16, 2016 19:35
-
-
Save coyl/7f4df52b49f1f7149bfaa724c0cb6c29 to your computer and use it in GitHub Desktop.
How to test protected methods
This file contains hidden or 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
/** | |
* 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