Jan 11

how to access private property october cms

Once I was also stumbled upon one specific issue, where I wanted to access the private property of the class. Unfortunately, that property was private property.

I can not make that property public as it was a third-party library. so it was like I was stuck there.

But weird thing was that when I do dd - dump and die function dd($class) which was available in `October cms and the Laravel already surprisingly it was printed there. I was just curious how this debug function can access that private property and print it ?

So I debug it a little and find its source code I am not going in deep how it works uisng PHP ReflectionClass. but it was working and I can see that private property.

For example there is class and it has private property
class myClass {
    private $privateVariable = 'secret';

Now lets try to access $privateVariable but it will throw an error Cannot access private property,

We are creating new instance of myClass and try to access private property
$class = new myClass();
// Cannot access private property Hardiksatasiya\So\myClass::$privateVariable

Now let's apply our trick, and surprisingly you are able to access that private property.

We are applying our trick to access privateVariable
use Symfony\Component\VarDumper\Cloner\VarCloner;

$class = new myClass();

$cloner = new VarCloner();
$clonedClass = $cloner->cloneVar($class);
dd($clonedClass->privateVariable); // -> outputs `secret`

you may find this useful when you do not want to change the third-party code and you still want to access private property you can use this trick.