PHP通过引用传递数组

时间:2010-12-12 16:05:54

标签: php arrays reference

  1. 在PHP中使用array_splice的正确方法是什么?函数标题清楚地说:

    array_splice ( array &$input , int $offset...所以它应该接受引用作为第一个参数。

    然而,一行

    array_push(&$this->contextsIds, $contextId);

    触发错误已弃用:已在...第132行弃用了电话时间传递引用

  2. 如何返回对数组的引用?我有:

    public function &getContextsIds() {
        return is_array($this->contextsIds) ? $this->contextsIds : array();    
    }
    

    但它说注意:只应通过引用返回变量引用

2 个答案:

答案 0 :(得分:7)

  1. 该函数已声明为引用(array &$input);调用函数时,您不需要再次&。只需将其称为:

    array_push($this->contextsIds, $contextId);
    
  2. 正如消息所说,您应该只通过引用返回实际变量,而不仅仅是值。在您的示例中,有两个这样的实例:? :运算符求值为一个值,而array()本身也只是一个未绑定到任何变量的值。您应该只是返回您的类成员,无论它是否为空:

    return $this->contextIds;
    

答案 1 :(得分:1)

为什么要返回对数组的引用,尤其是在您提供的代码中:

public function &getContextsIds() {
    return is_array($this->contextsIds) ? $this->contextsIds : array();    
}

当该函数可以工作时,它可以返回对空数组的引用,我可以用它做我想要的并按照我的意愿更改它,但它不会有任何影响,因为它只是一个空数组,没有任何进一步的参考..