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.