This feature is called overloading
in PHP. As the documentation states the __get
or __set
methods will be called if you are trying to access non existent or non accessible properties. The problem in your code is, that the properties your are accessing are existent and accessible. That's why __get
/__set
will not being called.
Check this example:
class Test {
protected $foo;
public $data;
public function __get($property) {
var_dump(__METHOD__);
if (property_exists($this, $property)) {
return $this->$property;
}
}
public function __set($property, $value) {
var_dump(__METHOD__);
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
}
Test code:
$a = new Test();
// property 'name' does not exists
$a->name = 'test'; // will trigger __set
$n = $a->name; // will trigger __get
// property 'foo' is protected - meaning not accessible
$a->foo = 'bar'; // will trigger __set
$a = $a->foo; // will trigger __get
// property 'data' is public
$a->data = '123'; // will not trigger __set
$d = $a->data; // will not trigger __get