Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ReflectionProperty::setAccessible make the property forever accessible?

Tags:

php

reflection

I would like to have a private property in a class, and be able to set it with another, via a ReflectionClass.

I know that if I create ReflectionProperties of the class' properties, I can set them to accessible, and then set their values.

However, if I set the property to accessible, does it become accessible everywhere (like a public property), or is it just in the context of the ReflectionProperty?

like image 579
johnnietheblack Avatar asked Mar 23 '12 07:03

johnnietheblack


1 Answers

It will only be accessible through the ReflectionProperty::getValue() and ReflectionProperty::setValue(), so the original class and all its instances will not have their visibility changed.

Example:

    <?php

    class MyClass {
       public function __construct() { $this->priv = 42; }
       private $priv;
    }

    $a = new MyClass();

    $ref = new ReflectionClass("MyClass");

    $prop = $ref->getProperty("priv");
    $prop->setAccessible(TRUE);

    echo "priv: " . $prop->getValue($a) . "\n";  // OK!

    echo $a->priv;                               // <-- error
    ?>
like image 105
Weston Avatar answered Sep 17 '22 14:09

Weston