Hello.

Tell me, please, why this code does not issue NOTICE?

error_reporting(E_ALL); $v = NULL; echo $v[0]; 

Accordingly, if $ v is not declared as NULL, then there will be a Notice: Undefined variable: v in

Thank.

  • The variable is defined, so there should be no notes. PS $ null = NULL; // this variable is defined as NULL $ empty = ""; // defined, but "empty" $ true = TRUE; // defined, not NULL and "notempty" unset ($ undefined); // this variable is not defined - Deonis
  • You can apply an echo or take an index to any object, even NULL. It is true that it is impossible to apply operations to non-initialized (where there is no equals), and therefore not to existing variables. - Alex Krass
  • @Deonis, NULL [0], in my opinion, should produce quite a clear error that null is not a variable with array access. Though at me returns NULL. Fun stuff. - etki
  • @Etki, I did not delve into this paradox. Although, if we can refer to any value (string, array) by index, then why can't the value of "nothing" be addressed in the same way? "nothing" [100500] - all the same " nothing ". Brad, I suppose, but I don’t undertake another explanation. )) - Deonis
  • It seems to me that all simple types are inherited from a single Object class, in which, by default, the correct behavior for addressing by index is already established. Otherwise, why would such a code suddenly work? error_reporting (E_ALL); $ v = NULL; $ v [0] = "~ oh shi"; echo $ v [0]; // Suddenly prints ~ oh shi $ b = NULL; $ b ["Chock-chock"] = "Hi;)"; echo $ b ["Chock-chock"]; // It is no longer so suddenly outputting Hi;) But I will leave the search for the truth to someone else who has the desire to dig the source code. - Alex Krass

1 answer 1

The answer was quite simple. When PHP doesn't like something, it converts the type. At what to understand, when this transformation on the fly is valid, and when not valid, it seems impossible. In short:

Converting NULL to an array results in an empty array.

http://php.net/manual/en/language.types.array.php

and another funny line from the same:

Null will be the keyed string.

When trying to set an index, PHP looks at a variable, finds NULL , considers it to be equivalent to an array , converts it to an empty array, and sets a value. The notification does not appear, because according to the developers philosophy, NULL is identical to the array . But they could notch.

Evidence:

 $a = null; $a[0] = 'What the hell?'; var_dump(null == array(), $a == null, gettype($a), $a); /* bool(true) bool(false) string(5) "array" array(1) { [0] => string(14) "What the hell?" } */ 

ps although it is still not clear why access to a nonexistent index is not accompanied by a notification.

pps uiiiiiiiiiiiiiiiiiiii

 $varA = null; for ($i = 0; $i < 999; $i++) { $varA = $varA[$i]; // $varB = null[$i]; // вот заметьте, здесь он ругнется на невалидный синтаксис } var_dump($varA /*, $varB*/);