Search code examples
phpoopinheritancemagic-methods

About PHP Magic Methods __get and __set on inheritance


OBS: I coded directly here, beacause my code is much more complex.

If I code:

class SuperFoo {
    public function __get($name) {
        return $this->$name;
    }
    public function __set($name, $value) {
        $this->$name = $value;
    }
}

class Foo extends SuperFoo {
    private $bar = '';
}

$foo = new Foo();
$foo->bar = "Why it doesn't work?";
var_dump($foo);

Results in:

object(Foo) {
    ["bar":"Foo":private]=> 
        string(0) ''
}

And not in:

object(Foo) {
    ["bar":"Foo":private]=> 
        string(20) 'Why it doesn't work?'
}

Why this happen? I don't want to use an array to hold the attributes, because I need them declared as individual private members.


Solution

  • Your code should be resulting in a fatal error because you're trying to access a private property. Even before that, you should receive a syntax error because you haven't properly declared your functions. Hence, you're "resulting" var dump can never occur.

    Edit:

    You've edited your question. The reason it doesn't work is because bar is private to Foo (SuperFoo cannot access it). Make it protected instead.