[英]What does [] mean when reading from a PHP array?
I've been writing a parser for PHP and while messing around with some third-party code, I run into a weird case regarding the []
operator. 我一直在为PHP写一个解析器,虽然搞乱了一些第三方代码,但我遇到了一个关于
[]
运算符的奇怪案例。
Normally, []
is used without a key on the left side of an assignment meaning "add as the last element". 通常,在赋值左侧没有键的情况下使用
[]
,意思是“添加为最后一个元素”。
$a = array();
$a[] = 1;
will add 1 in the end of array $a. 将在数组$ a的末尾添加1。
In the aforementioned code though, I saw a line like this: 在前面提到的代码中,我看到了这样的一行:
$r =& $a[];
When I tried to remove the &, I got a rather expected fatal error: 当我试图删除&时,我得到了一个相当预期的致命错误:
Fatal error: Cannot use [] for reading
致命错误:无法使用[]进行阅读
With the &
though, PHP does not complain at all. 随着
&
不过,PHP不会抱怨的。 What is the meaning of the expression 表达式的含义是什么?
& $a[];
? ?
The syntax means "use a reference to $a[]" or a reference to the newest created array element. 语法意味着“使用对$ a []的引用”或对最新创建的数组元素的引用。
<?php
$a=array( );
$a[] = "a";
$a[] = "b";
print_r($a);
$r =& $a[];
print_r($a);
$r = "c";
print_r($a);
produces: 生产:
Array
(
[0] => a
[1] => b
)
Array
(
[0] => a
[1] => b
[2] =>
)
Array
(
[0] => a
[1] => b
[2] => c
)
My guess is that it adds an empty element to the array and gives $ra reference to that array element. 我的猜测是它向数组中添加了一个空元素,并为该数组元素提供$ ra引用。 Are you sure $a is supposed to be an array?
你确定$ a应该是一个数组吗? It could also be trying to access a character of a string using the [] syntax, in which case I have no idea how that would work.
它也可能尝试使用[]语法访问字符串的字符,在这种情况下我不知道这将如何工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.