Last active
May 4, 2018 04:40
-
-
Save maxgaurav/b9ffdb2796fc62cbc4eb1973916bc59a to your computer and use it in GitHub Desktop.
Reflection Method Example
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
class ABC { | |
protected function test() | |
{ | |
echo "Will not echo from an instance for protected"; | |
} | |
private function otherTest($content) | |
{ | |
echo "WIll not echo from an instance for private and content is $content"; | |
} | |
} | |
$obj = new ABC(); | |
//will throw error | |
$obj->test(); | |
//will throw error | |
$obj->otherTest("The Content"); | |
//Solution to make any private or protected method of an object instance accessible | |
$reflection = new \ReflectionClass($obj); | |
$method = $reflection->getMethod("test"); | |
$method->setAccessible(true); //the main action | |
$method->invoke($obj); | |
$otherMethod = $reflection->getMethod("otherTest"); | |
$otherMethod->setAccessible(true); | |
$otherMethod->invoke($obj, "The Content"); parameters then passed as comma seperation like normal method calling |
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
class ABC { | |
protected function test() | |
{ | |
echo "Will not echo from an instance for protected"; | |
} | |
private function otherTest($content) | |
{ | |
echo "WIll not echo from an instance for private and content is $content"; | |
} | |
} | |
$obj = new ABC(); | |
//will throw error | |
$obj->test(); | |
//will throw error | |
$obj->otherTest("The Content"); | |
//Solution to make any private or protected method of an object instance accessible | |
$method = new \ReflectionMethod($obj, "test"); | |
$method->setAccessible(true); //the main action | |
$method->invoke($obj); | |
$method = new \ReflectionMethod($obj, "testOther"); | |
$otherMethod->setAccessible(true); | |
$otherMethod->invoke($obj, "The Content"); parameters then passed as comma seperation like normal method calling |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment