Why doesn't php complain when referencing a nonexistent variable?

I was wondering why php doesn't complain when it refers to a non-existent variable (being a simple variable or an array), is it the way it is, or is there something else that I am missing? For example, this code

<?php $t = &$r["er"]; var_dump($r); ?> 

does not warn of a variable that does not exist.

In addition, var_dump shows this:

 array(1) { ["er"]=> &NULL } 

that &NULL is something that I really did not expect, I thought I was getting a simple NULL .

Thanks in advance!

+6
source share
2 answers

If the memory of the link to the PHP link interpreter var suits me, PHP will create a null element in the hash table with a key similar to the one you sent, and refer to it. This can be seen by running the following test:

 <?php $i = 0; $arr = []; $arrS = null; $v = memory_get_peak_usage(); for ($i = 0; $i < 150; $i++) { $arrS = &$arr[rand()]; } $v = memory_get_peak_usage() - $v; echo $v; 

To the default heap size, PHP will return exactly 0 extra memory used - since it still allocates already prepared array elements (PHP keeps a few extra hash table elements empty, but is assigned to improve performance). You can see this by setting it in the range of 0 to 16 (this is the heap size!).

When you get more than 16, PHP will have to allocate additional elements and will do this on i = 17, i = 18, etc., creating null elements to refer to them.

PS: contrary to what people say, it does NOT issue an error, warning or notification. Calling an empty element without a link - no reference to a nonexistent element. Big big big difference.

+5
source

does not warn of a variable that does not exist.

Here's how links work. $a = &$b; creates $b if it doesn’t exist yet, for future reference, if you like. It is similar to the parameters that are passed by reference. Perhaps this looks familiar to you:

 preg_match($pattern, $string, $matches); 

Here, the third parameter is a reference parameter, so $matches should not exist during a method call, but it will be created.

that & NULL is something that I really did not expect, I thought I was getting a simple NULL.

Why didn’t you expect this? $r['er'] is a link to / from $t . Note that references are not pointers, $r['er'] and $t are equal references to the same value, there is no direction from one to another (hence, quotation marks in the last sentence).

+1
source

All Articles