How to implement the _isset magic method?

I am trying to implement a __isset magic method such as the following code,

Why do I always get an undefined index error? can anyone tell me how to do this?

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 

Why does the following code work? I do not understand?

 $x = array(); var_dump(isset($x->a->b->c)); var_dump(isset($x['a']['b']['c'])); 
+4
source share
2 answers

You can expect the PHP engine to call __isset() before each property access is hidden in PHP. But this is not true . Check the documentation :

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

So this is the expected behavior as soon as:

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

will call __isset() .

All other lines will just call __get() . And since you did not set these indexes, this is the expected behavior.

Change your code to:

 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]); } } 

to see which methods are actually being called. This will give you:

 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) 
+1
source

You have a poorly implemented __get

 $c = new c(); var_dump(isset($c->a)); // false var_dump(isset($c->a->b)); // false var_dump(isset($c->b->c)); // false var_dump(isset($c->d['e'])); // false class c { public $x = array(); public function __get($name) { return isset($name) ? $this->x[$name] : null; } public function __isset($name) { return isset($this->x[$name]); } } 
+2
source

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


All Articles