Access private Variable and private Method from outside of Class in PHP

Today I have learnt how to access private variable and private method from outside of a php class. It is by using a built-in class “ReflectionClass”.

Here is the code-snippet:

Class Demo
    private $myPrivateVariable = 'I am Private Variable';
	public function myPublicMethod()
        return 'I am Public Method';

    private function myPrivateMethod()
        return 'I am Private Method';

$demo = new Demo();

//$reflection_class = new ReflectionClass('Demo');
$reflection_class = new ReflectionClass($demo);

$private_method = $reflection_class->getMethod('myPrivateMethod');
echo $private_method->invoke($demo);
// I am Private Method

$private_variable = $reflection_class->getProperty('myPrivateVariable');
echo $private_variable->getValue($demo);
// I am Private Variable

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s