数组中的项目,它们是引用吗?
看下面的代码:
$index = GetIndexForId($itemid);
$item = null;
if( $index == -1 )
{
$item = array();
$this->items[] = $item;
$index = count($this->items)-1;
}
else
$item = $this->items[$index];
$item['id'] = $itemid;
$item['qty'] = $qty;
$item['options'] = $options;
$this->items[$index] = $item; // This line is my question
最后一行,有必要吗?我真的不知道php如何处理数组分配。
PS GetIndexForId 只是搜索当前 ID 是否已存在于数组中,其他“未声明”变量是参数。
look at the code below:
$index = GetIndexForId($itemid);
$item = null;
if( $index == -1 )
{
$item = array();
$this->items[] = $item;
$index = count($this->items)-1;
}
else
$item = $this->items[$index];
$item['id'] = $itemid;
$item['qty'] = $qty;
$item['options'] = $options;
$this->items[$index] = $item; // This line is my question
The last line, is it necessary? I really dont know how php handles array assignment.
P.S. GetIndexForId just searches for if the current ID already exists in the array, and the other "undeclared" variables are parameters.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
来自文档:
所以是的,考虑到您的代码,最后一行是必要的,但是
$this->items[] = $item;
是多余的。From the documentation:
So yes, given your code, the last line is necessary, but
$this->items[] = $item;
is superfluous.如果你想更新你的对象,是的,你需要最后一行
If you want to update your Object, yes you need this last line
任何值类型(如 boolean、int...)都不会通过引用传递。但是如果你的数组充满了对象,它将通过引用传递。在您的示例中,您需要最后一行。但正如我所说,如果 $item 是一个对象,则不需要最后一行。可以使用引用运算符通过引用传递值类型。
了解如何使用引用运算符
此处
Any value type like boolean, int... will not be passed by reference. But if your array is filled with objects, it WILL be passed by reference. In your exemple, you need the last line. But as I said, if $item were an object you wouldn't need the last line. It is possible to pass a value type by reference with the reference operator.
Learn how to use the reference operator
HERE