I tried the following code in both facebook’s phpsh and the standard crappy php -a abomination for a repl:
$a = NULL;
echo $a['foobar'];
To my regret (I wouldn’t call it surprise or disappointment when it concerns PHP) I don’t get any errors or warnings or exceptions or anything.
Smarter languages like Ruby and Python both complain when trying to dereference a key from eg None or nil. How is PHP interpreting this situation? Is the only cure inserting is_null checks everywhere? Should I blame Smarty for not doing it for me?
According to PHP source code (
Zend/zend_execute.c), only strings, arrays and objects can trigger errors when accessing an offset/index. The rest is more-or-less ignored:None of
$a,$b,$c,$dor$eactually spit an error. Most of the times in the code I just seereturn;orreturn 0;, which means NULL, instead of a returnedzval*(pointer) orzend_error()call. Hence the results above.Whatever the reason why it has been done like this, it doesn’t really matter. You should always check a variable for existence and/or nullity in such cases. The safest ways (slightly different behaviours) are
issetandempty: