Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 990
Ramon K. Avatar asked Feb 17 '23 19:02

Ramon K.


2 Answers

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.

like image 116
webbiedave Avatar answered Feb 26 '23 22:02

webbiedave


__get($name) isn't called if object has attribute called $name, but it tries to use the attribute directly. And your attribute is private, thus error.

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

like image 34
Vyktor Avatar answered Feb 27 '23 00:02

Vyktor