Created
July 18, 2017 06:34
-
-
Save legend80s/c48c109f10007be1f488fb0b30f8ffb7 to your computer and use it in GitHub Desktop.
Call protected/private static method of a class. Used usually in Unit Test.
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
<?php | |
trait MethodInvoker { | |
/** | |
* Call protected/private static method of a class. | |
* | |
* @param string $class - class name that we will run method on | |
* @param string $methodName - method name to call | |
* @param array $parameter - parameter to pass into method | |
* | |
* @return mixed - original method's return | |
*/ | |
public static function invokeStaticMethod($class, $methodName) | |
{ | |
$reflectionClass = new ReflectionClass($class); | |
$method = $reflectionClass->getMethod($methodName); | |
$method->setAccessible(true); | |
// get all the parameters after $methodName | |
$parameters = array_slice(func_get_args(), 2); | |
return $method->invokeArgs(null, $parameters); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: