为什么当我把一个空值作为一个这样的数组并没有PHP抱怨吗? [英] Why does PHP not complain when I treat a null value as an array like this?

查看:130
本文介绍了为什么当我把一个空值作为一个这样的数组并没有PHP抱怨吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,我有 的error_reporting 设定报告一切,包括通知。

In PHP, I have error_reporting set to report everything including notices.

为什么不下面扔任何通知,错误或别的什么吗?

Why does the following not throw any notices, errors or anything else?

$myarray = null;
$myvalue = $myarray['banana'];

故障排除步骤:

$myarray = array();
$myvalue = $myarray['banana'];
// throws a notice, as expected ✔

$myarray = (array)null;
$myvalue = $myarray['banana'];
// throws a notice, as expected ✔

$myarray = null;
$myvalue = $myarray['banana'];
// no notice or warning thrown, $myvalue is now NULL. ✘ Why?

这是可能的它在PHP中的错误,或者我只是不理解的东西如何工作的。

It's possible it's a bug in PHP, or I'm just not understanding something about how this works.

推荐答案

通常,当你尝试就好像它是另一种类型使用一种类型的值,要么是错误或警告被抛出或式的杂耍发生。例如,如果你试图用来连接两个数字。,他们都会得到强制转换为字符串,然后连接起来。

Usually, when you try to use a value of one type as if it were another type, either an error or warning gets thrown or "type juggling" takes place. For example, if you try to concatenate two numbers with ., they'll both get coerced to strings and concatenated.

不过,在手册页约杂耍式的解释< /一>,这不是一种治疗非阵列等的阵列时的情况:

However, as explained on the manual page about type juggling, this isn't the case when treating a non-array like an array:

自动转换为数组的行为目前是不确定的。

The behaviour of an automatic conversion to array is currently undefined.

在实践中,这种情况发生时,这种不确定的行为是取消对非数组引发的行为是获取返回,因为你所观察到的。这不仅影响空 - 你会还可以获得如果您尝试取消引用一个数字或资源

In practice, the behaviour that happens when this "undefined behaviour" is triggered by dereferencing a non-array is that null gets returned, as you've observed. This doesn't just affect nulls - you'll also get null if you try to dereference a number or a resource.

这篇关于为什么当我把一个空值作为一个这样的数组并没有PHP抱怨吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆