Strange PHP magic getter on an array

I have weird problems with getter / isset magic. I have myObject that defines magic getter / isset:

private $_data = array();

public function __get($name) {
    if (array_key_exists($name, $this->_data)) return $this->_data[$name];
    throw new Exception($name.': property doesn\'t exist.');
}

public function __isset($name) {
    return isset($this->_data[$name]);
}

If I call:

isset($myObject->notExisting);
empty($myObject->notExisting);

I have the correct behavior (__isset () is called), and if I call:

isset($myObject->notExisting['ok']));
empty($myObject->notExisting['ok']));

__ isset () is not called, but __get ().

This seems strange to me, since PHP must first check for the existence of $ myObject-> notExisting before trying to get it, right?

+4
source share
2 answers

According to docs :

__ isset () is triggered by isset () or empty () call for inaccessible properties.

in isset($myObject->notExisting);isset applies to a property notExisting $myObject.

in isset($myObject->notExisting['ok'])); isset ok $myObject->notExisting.

+3

.

:

isset($myObject->notExisting['ok']));

, $myObject- > notExisting, "ok". , __get().

+1

Source: https://habr.com/ru/post/1626125/


All Articles