Way To Access Private Property Or Method In PHP

Hello PHP Developers in this tutorial i am going to show you an awesome thing that is how you can access private property or method in php. Generally we know that it is not possible to access private property or method outside of a class.

We use private properties because of hiding our data outside of class. But you know in certain scenarios, you might want to access these private members outside of the class. In this example i will show you the way of access private property in php.

First, Look at the following class.

class Foo 
{
    private function privateMethod() {
        return 'howdy';
    }
}

$foo = new Foo;
$foo->privateMethod(); 

 

If you run this code it will generate the following errors like

 

OUTPUT
// Fatal error: Uncaught Error: Call to private method // Foo::privateMethod() from context

 

But if you run this code like the below ways

$reflectionMethod = new ReflectionMethod('Foo', 'privateMethod');
$reflectionMethod->setAccessible(true);

echo $reflectionMethod->invoke(new Foo); 

 

Then it will give us the required output. 

 

OUTPUT
howdy

 

Look i just used PHP’s in-built ReflectionMethod class which can give handlful of information about the class. Basically, it shows the “mirror” to the class. 

 

If you want to access private property outside of a class then follow the below code.

class Foo 
{
    private $privateProperty = 'Code Cheef!';    
}

$method = new ReflectionProperty('Foo', 'privateProperty');
$method->setAccessible(true);

echo $method->getValue(new Foo);

 

Recommended : When to Choose Composition Over Inheritance in PHP

 

Hope it can help you.

 

 

#php #oop-php #access-specifier