为什么将整数作为数组($ int [$ index])不会在PHP中引起任何错误? [英] Why does treating integers as arrays ($int[$index]) not raise any errors in PHP?

查看:112
本文介绍了为什么将整数作为数组($ int [$ index])不会在PHP中引起任何错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于好奇,这只是一个简单的问题.我花了一整天的时间调试我的PHP代码,发现问题是由于将整数视为数组引起的:

This is just a simple question out of curiosity. I spent the whole day debugging my PHP code, and found the problem was due to treating an integer as an array:

$x = $int[$index]; // this returns null, but no error at all

该整数实际上是一个数组,但是用于传递数组的函数却搞砸了,而是传递了数组中的第一个值.有什么原因不会显示错误?访问数组上的未定义索引会产生错误,但是尝试访问整数上不存在的索引不会吗?

The integer was actually meant to be an array, but the function that was meant to pass the array messed up and passed the first value in the array instead. Is there any reason why an error isn't shown? Accessing an undefined index on an array creates an error, however trying to access a non-existent index on an integer doesn't?

推荐答案

我原本以为;它将$int类型转换为字符串,因为[]是访问字符串位置的另一种方法.看来不会产生错误是合理的:

I originally thought; it typecasts $int to a string because [] is another way of accessing string positions. Seems plausible that that wouldn't generate an error:

$string 'Hello';
echo $string[0]; // H

但是,事实并非如此:

$int = 1;
echo $int[0];

不输出任何内容,而var_dump($int[0])返回NULL.

Outputs nothing and var_dump($int[0]) returns NULL.

有趣的是,对于boolfloat表现出相同的行为,并且使用的操作是FETCH_DIM_R,这是从数组值"中的索引"处获取元素的值以进行存储在结果"中.

Interestingly, the same behavior is exhibited for bool and float and the operation used is FETCH_DIM_R which is Fetch the value of the element at "index" in "array-value" to store it in "result".

从手册数组:

注意:取消引用标量值的数组,该标量值不是

Note: Array dereferencing a scalar value which is not a string silently yields NULL, i.e. without issuing an error message.

类似于此现象,其中不会产生任何错误.错误#68110

Similar to this phenomenon, where no error is generated. Bugs #68110 and #54556:

$array['a'] = null;
echo $array['a']['non-existent'];

分配不起作用并不奇怪:

Not surprising that assigning doesn't work:

$int = 1;
$int[0] = 2;

警告:不能将标量值用作数组

Warning: Cannot use a scalar value as an array

因此,PHP实际上正在尝试以数组形式访问intboolfloat,但不会产生错误.至少是从4.3.0版到7.2.2版.

So PHP is actually attempting to access the int, bool, float as an array but not generating an error. This is from at least version 4.3.0 to 7.2.2.

这篇关于为什么将整数作为数组($ int [$ index])不会在PHP中引起任何错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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