How can I use __get() to return null in multilevel object property accessing the case like this below?
For instance, this is my classes,
class property
Yes, I know it's been 4 years ago, but I had a similar problem this week, and while I trying to solve it, I found this thread. So, here is my solution:
class NoneWrapper
{
private $data;
public function __construct($object)
{
$this->data = $object;
}
public function __get(string $name)
{
return property_exists($this->data, $name)
? new NoneWrapper($this->data->$name)
: new None;
}
public function __call($name, $arguments)
{
if (is_object($this->data)) {
return (property_exists($this->data, $name))
? $this->data->$name
: null;
} else {
return null;
}
}
public function __invoke()
{
return $this->data;
}
}
class None
{
public function __get(string $name) {
return new None;
}
public function __call($name, $arguments)
{
return null;
}
public function __invoke()
{
return null;
}
}
$object = new NoneWrapper(
json_decode(
json_encode([
'foo' => [
'bar' => [
'first' => 1,
'second' => 2,
'third' => 3,
'fourth' => 4,
],
]
])
)
);
var_dump($object->foo->bar->baz()); // null
var_dump($object->foo->bar->third()); // 3