如果尝试使用括号获取 NULL 上的键的值,为什么在 PHP 中不会出现错误?

发布于 2024-11-01 04:00:01 字数 308 浏览 11 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

橘味果▽酱 2024-11-08 04:00:02

根据 PHP 源代码 (Zend/zend_execute.c),只有字符串、数组和对象在访问偏移量/索引时才会触发错误。其余部分或多或少被忽略:

$a = true;
$b = false;
$c = null;
$d = 1;
$e = 1.234;
$f = '';
$g = array();
$h = new stdClass;

echo $a[0]; // NULL
echo $b[0]; // NULL
echo $c[0]; // NULL
echo $d[0]; // NULL
echo $e[0]; // NULL
echo $f[0]; // E_NOTICE: Uninitialized string offset
echo $g[0]; // E_NOTICE: Undefined offset
echo $h[0]; // E_FATAL:  Cannot use object as array

$a$b$c$d 都没有> 或 $e 实际上会吐出一个错误。大多数时候,在代码中我只看到 return;return 0;,这意味着 NULL,而不是返回的 zval* (指针) 或 zend_error() 调用。因此就有了上面的结果。

无论出于什么原因这样做,都并不重要。在这种情况下,您应该始终检查变量是否存在和/或无效。最安全的方法(行为略有不同)是isset和empty:

isset($a['foo']);
!empty($a['foo']);    

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:

$a = true;
$b = false;
$c = null;
$d = 1;
$e = 1.234;
$f = '';
$g = array();
$h = new stdClass;

echo $a[0]; // NULL
echo $b[0]; // NULL
echo $c[0]; // NULL
echo $d[0]; // NULL
echo $e[0]; // NULL
echo $f[0]; // E_NOTICE: Uninitialized string offset
echo $g[0]; // E_NOTICE: Undefined offset
echo $h[0]; // E_FATAL:  Cannot use object as array

None of $a,$b,$c,$d or $e actually spit an error. Most of the times in the code I just see return; or return 0;, which means NULL, instead of a returned zval* (pointer) or zend_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 and empty:

isset($a['foo']);
!empty($a['foo']);    
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文