编程语言
首页 > 编程语言> > php – 如何实现_isset魔术方法?

php – 如何实现_isset魔术方法?

作者:互联网

我尝试实现__isset魔术方法,如下面的代码,

为什么我总是得到一个未定义的索引错误?任何人都可以告诉我该怎么办?

class c {
    public $x = array();
    public function __get($name) {
        return $this->x[$name]; //undefined index: #1:a / #2:b / #3:d
    }
    public function __isset($name) {
        return isset($this->x[$name]);
    }
}

$c = new c;
var_dump(isset($c->a));      
var_dump(isset($c->a->b));   #1
var_dump(isset($c->b->c));   #2
var_dump(isset($c->d['e'])); #3

为什么以下代码工作正常?我不明白?

$x = array();
var_dump(isset($x->a->b->c));       
var_dump(isset($x['a']['b']['c']));

解决方法:

您可能希望PHP引擎在每次访问PHP中的隐藏属性之前调用__isset().但那不是真的.检查documentation

__isset() is triggered by calling isset() or empty() on inaccessible properties.

所以,这是预期的行为,仅作为:

var_dump(isset($c->a));

将触发__isset().

所有其他行只会触发__get().由于您没有设置这些索引,因此它是预期的行为.

将您的代码更改为:

class c {
    public $x = array();
    public function __get($name) {
        var_dump(__METHOD__);
        return $this->x[$name];
    }
    public function __isset($name) {
        var_dump(__METHOD__);
        return isset($this->x[$name]);
    }
}

查看实际调用的方法.这会给你:

c::__isset   <------ called!
bool(false)
c::__get

Notice: Undefined index: a in /tmp/a.php on line 6

Call Stack:
    0.0002     647216   1. {main}() /tmp/a.php:0
    0.0003     648472   2. c->__get() /tmp/a.php:16

<---------------------- not called 
bool(false)
c::__get

Notice: Undefined index: b in /tmp/a.php on line 6

Call Stack:
    0.0002     647216   1. {main}() /tmp/a.php:0
    0.0005     648656   2. c->__get() /tmp/a.php:17

<---------------------- not called     
bool(false)
c::__get

Notice: Undefined index: d in /tmp/a.php on line 6

Call Stack:
    0.0002     647216   1. {main}() /tmp/a.php:0
    0.0006     648840   2. c->__get() /tmp/a.php:18

<---------------------- not called     
bool(false)

标签:php,magic-methods
来源: https://codeday.me/bug/20190629/1327487.html