Skip to content

Instantly share code, notes, and snippets.

@maxgaurav
Last active May 4, 2018 04:40
Show Gist options
  • Save maxgaurav/b9ffdb2796fc62cbc4eb1973916bc59a to your computer and use it in GitHub Desktop.
Save maxgaurav/b9ffdb2796fc62cbc4eb1973916bc59a to your computer and use it in GitHub Desktop.
Reflection Method Example
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
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