如果尝试使用括号获取 NULL 上的键的值,为什么在 PHP 中不会出现错误?
我在 facebook 的 phpsh 和标准的蹩脚 php -a abomination for a repl 中尝试了以下代码:
$a = NULL;
echo $a['foobar'];
遗憾的是(当涉及 PHP 时,我不会称其为惊喜或失望)我没有收到任何错误、警告或异常或任何东西。
Ruby 和 Python 等更智能的语言在尝试从 None 或 nil 等取消引用键时都会抱怨。 PHP 如何解释这种情况?唯一的解决方法是在各处插入 is_null 检查吗?我应该责怪 Smarty 没有为我做这件事吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据 PHP 源代码 (
Zend/zend_execute.c
),只有字符串、数组和对象在访问偏移量/索引时才会触发错误。其余部分或多或少被忽略:$a
、$b
、$c
、$d
都没有> 或$e
实际上会吐出一个错误。大多数时候,在代码中我只看到return;
或return 0;
,这意味着 NULL,而不是返回的zval*
(指针) 或zend_error()
调用。因此就有了上面的结果。无论出于什么原因这样做,都并不重要。在这种情况下,您应该始终检查变量是否存在和/或无效。最安全的方法(行为略有不同)是isset和empty:
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
,$d
or$e
actually 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
isset
andempty
: