问题描述
为什么会出现以下情况
$a = new SplFixedArray(5);$a[0] = 数组(1, 2, 3);$a[0][0] = 12345;//这里var_dump($a);
生产
注意:间接修改SplFixedArray的重载元素对没有影响.在线<指示>
这是一个错误吗?那么你如何处理多维 SplFixedArrays 呢?有什么解决方法吗?
首先,问题与所有实现ArrayAccess
的类有关,不是SplFixedArray
的特殊问题> 仅.
当您使用 []
运算符从 SplFixedArray
访问元素时,它的行为与数组不完全相同.在内部调用 offsetGet()
方法,并且在您的情况下将返回一个数组 - 但不是对该数组的引用.这意味着您对 $a[0]
所做的所有修改都将丢失,除非您将其保存回来:
解决方法:
$a = new SplFixedArray(5);$a[0] = 数组(1, 2, 3);//获取元素$element = $a[0];//修改它$元素[0] = 12345;//再次存储元素$a[0] = $element;var_dump($a);
这是一个使用标量的示例,它也失败了 - 只是为了向您展示它不仅仅与数组元素相关.>
Why the following
$a = new SplFixedArray(5);
$a[0] = array(1, 2, 3);
$a[0][0] = 12345; // here
var_dump($a);
produces
Notice: Indirect modification of overloaded element of SplFixedArray has no effect in <file> on line <indicated>
Is it a bug? How do you deal with multidimensional SplFixedArrays then? Any workarounds?
First, the problem is related to all classes which implement ArrayAccess
it is not a special problem of SplFixedArray
only.
When you accessing elements from SplFixedArray
using the []
operator it behaves not exactly like an array. Internally it's offsetGet()
method is called, and will return in your case an array - but not a reference to that array. This means all modifications you make on $a[0]
will get lost unless you save it back:
Workaround:
$a = new SplFixedArray(5);
$a[0] = array(1, 2, 3);
// get element
$element = $a[0];
// modify it
$element[0] = 12345;
// store the element again
$a[0] = $element;
var_dump($a);
Here is an example using a scalar which fails too - just to show you that it is not related to array elements only.
这篇关于“间接修改 SplFixedArray 的重载元素没有效果"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!