Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reasons for basic __get implementation

Other similar questions:

Why I should use __get() and __set()-magic methods in php?
When do/should I use __construct(), __get(), __set(), and __call() in PHP?

First, I completely understand how to implement __get and __set methods in PHP and have come across scenarios where using these methods is beneficial.

However, I have encountered, and written, code that looks like the following:

class SomeObject {

    protected $data = array();

    public function __set($key, $val) {
        $this->data[$key] = $val;
    }

    public function __get($key) {
        return $this->data[$key];
    }

}

Why do we need to do this? I have used objects with no __get or __set methods defined and can still add undefined properties, retrieve the values associated with those properties, invoke isset() and unset() on those properties.

Do we really need to implement these magic methods, using code like above, when objects in PHP already exhibit similar behavior?

Note, I'm not referring to when more code is used in the __set and __get methods for special handling of the data requested but very basic implementation like the code above.

like image 227
Charles Sprayberry Avatar asked Sep 10 '26 00:09

Charles Sprayberry


2 Answers

If you are using them just as a glorified wrapper over an array (i.e. absolutely no extra logic), I don't believe they offer any benefit. They do offer a drawback however, in that you need to write the code for them. And that code may be buggy or incomplete.

Did you leave out __isset for brevity? Because if you do use __get and __set but do not provide an __isset, you 've just written yourself a bug.

See what I did there?

like image 196
Jon Avatar answered Sep 12 '26 14:09

Jon


In the example you gave, it's very easy to overwrite $data with a new array. If you were dealing with properties, you would have to iterate over an array and perform $this->$key = $data; (to which you may have data leakage).

In more detail:

protected function setData($arr)
{
   $this->data = $arr;
}

vs.

protected function setData($arr)
{
    foreach($arr as $key => $data)
    {
        $this->$key => $data;
    }
}

With the example above, keys which don't appear in $arr in the current call, but have in previous calls, will not be overwritten, which can lead to undesired results.

In the end, it just depends on what makes the most sense for you.


As a side note, in the example code you gave, you should be sure you're implementing __isset() when you have __get(). If you don't, you'll get unexpected results when using functions like isset() or empty().