Search code examples
phpclassobjectdata-members

Update values of all public variables of class using get_object_vars()


I have class with 100 public members. How can I update them in an automated way, ie without specifying their name. I have tried this and I'm getting variables but the changes made doesn't reflect on actual object. Please advice.

    class foo {
    public $b = 1;
    public $c = 2;


    function __construct()
    {
        $x = get_object_vars($this);
        foreach ($x as $obj) {
                 $obj = 9;
        }
    }
}

$test = new foo;

echo $test->c;

It prints vale of 'c' as 2 instead of 9


Solution

  • function __construct()
    {
        $x = get_object_vars($this);
        foreach ($x as $key => $value) {
            $this->$key = 9;
        }
    }