How does PHP detect infinite recursion?

Possible duplicate:
How does PHP avoid infinite recursion here?

Someone posted this as php #wtf on Twitter:

class A { private $b; function __construct() { unset($this->b); } function __get($n) { echo '!broken!'; return $this->$n; } } $a = new A; $a->b; //EDIT: original question had var_dump($a->b); //output: !broken!!broken! 

My first answer to this is that $ a-> b fires __get () for the first echo, and then returns $ this → $ n triggers __get calls $ this-> b again, but there is no code, which is supposedly contained in __get (). PHP automatically detects infinite recursion and stops there. This makes sense, but on the other hand, PHP gives an E_NOTICE error for the underfunded property A :: $ b.

So my question is: am I correcting that PHP automatically detects infinite recursion? How can i say Or is there another reason to explain this result?

+4
source share
1 answer

Private variables are not hidden in the class. So, when executing the code below, you can get the $ b variable without calling __get ():

 class A { private $b; function get_b() { return $this->b; } } $a = new A; echo $a->get_b(); 

But below, you cannot - it will call the __get () function:

 class A { private $b; function get_b() { return $this->b; } } $a = new A; echo $a->b; 

So in your example:

class A {private $ b;

 function __construct() { unset($this->b); } function __get($n) { echo '!broken!'; return $this->$n; } } 
 $a = new A; // Here you called unset, and since it doesn't know the "b", it calls __get(). var_dump($a->b); // Again here $a->b is not "exists" or "hidden", so it calls __get() again. 

In __get (), return $ this → $ n "know the variable $ n - that is, $ b (as in my first code example, the get_b () function). So this is not infinite recursion, it is like any other function that calls ;)

0
source

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


All Articles