简体   繁体   English

为什么在布尔值上访问数组索引不会引发任何类型的错误?

[英]Why does accessing array index on boolean value does not raise any kind of error?

When I try to access an array by key which is not exists in this array, php will raise "undefined index" notice error. 当我尝试通过该数组中不存在的键访问数组时,php将引发“未定义的索引”通知错误。 When I try to do the same on strings, "Illegal string offset " warning is raised. 当我尝试对字符串执行相同操作时,会出现“非法字符串偏移”警告。 This is an expected behavior and I know how to deal with it. 这是一种预期的行为,我知道如何处理它。

But when I tried this on boolean or integer values nothing happens: 但是当我在布尔值或整数值上尝试这个时,没有任何反应:

ini_set('display_errors', 1);
error_reporting(E_ALL);

$var = false;
var_dump($var['test']);

I expect to see some error messages, but $var['test'] just silently sets to NULL. 我希望看到一些错误消息,但$var['test']只是静默设置为NULL。

So why does php permit to access boolean value through an array key without any indication that you are doing something wrong? 那么为什么php允许通过数组键访问布尔值而没有任何迹象表明你做错了什么? The hole "access boolean value through an array key" phrase sounds terribly wierd to me, but you can do it in php. 洞“通过数组键访问布尔值”这句话对我来说听起来非常奇怪,但你可以在php中完成。

It's sad, but it's documented behaviour. 这很难过,但它是记录在案的行为。

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

Note: 注意:

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL. 使用[]或{}以静默方式访问其他类型的变量(不包括实现适当接口的数组或对象)将返回NULL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM