为什么访问布尔值的数组索引不会引发任何类型的错误? [英] Why does accessing array index on boolean value does not raise any kind of error?

查看:43
本文介绍了为什么访问布尔值的数组索引不会引发任何类型的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试通过该数组中不存在的键访问数组时,php 将引发未定义索引"通知错误.当我尝试对字符串执行相同操作时,会引发非法字符串偏移"警告.这是预期的行为,我知道如何处理.

When I try to access an array by key which is not exists in this array, php will raise "undefined index" notice error. 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']);

我希望看到一些错误消息,但 $var['test'] 只是默默地设置为 NULL.

I expect to see some error messages, but $var['test'] just silently sets to NULL.

那么为什么 php 允许通过数组键访问布尔值而没有任何迹象表明您做错了什么?通过数组键访问布尔值"这句话对我来说听起来很奇怪,但你可以在 php 中做到这一点.

So why does php permit to access boolean value through an array key without any indication that you are doing something wrong? The hole "access boolean value through an array key" phrase sounds terribly wierd to me, but you can do it in php.

推荐答案

这很可悲,但它已记录在案.

It's sad, but it's documented behaviour.

http://php.net/manual/en/language.types.字符串.php

注意:

使用 [] 或 {} 访问其他类型的变量(不包括实现适当接口的数组或对象)会静默返回 NULL.

Accessing variables of other types (not including arrays or objects implementing the appropriate interfaces) using [] or {} silently returns NULL.

这篇关于为什么访问布尔值的数组索引不会引发任何类型的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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