Daily Archives: August 27, 2013

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