PHP如何通过引用传递数组

3
  1. What is a correct way to use array_splice in PHP? The function header clearly says:

    array_splice ( array &$input , int $offset... so it should accept reference as a first argument.

    However, a line

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

    Triggers an error Deprecated: Call-time pass-by-reference has been deprecated in ... line 132

  2. How do I return a reference to an array? I have:

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

    but it says Notice: Only variable references should be returned by reference

2个回答

7
  1. The function is already declared to take a reference (array &$input); you don't need the & again when calling the function. Just call it like this:

    array_push($this->contextsIds, $contextId);
    
  2. As the message says, you should only return actual variables by reference, not mere values. In your example, there are two such instances: the ? : operator evaluates to a value, and also array() by itself is just a value not bound to any variable. You should probably just return your class member regardless of whether it is empty or not:

    return $this->contextIds;
    

谢谢!你能帮我处理我添加的第二个问题吗? - tillda
无论它是否为空,他正在测试 is_array() - BoltClock
@BoltClock:我注意到了,但我猜他可能是在测试它是否为空。我会等待原帖作者的回复。 - casablanca

1
为什么你会返回一个数组的引用,尤其是在你提供的代码中?
public function &getContextsIds() {
    return is_array($this->contextsIds) ? $this->contextsIds : array();    
}

当该函数工作时,它可以返回一个空数组的引用,我可以随意更改它,但它不会产生任何影响,因为它只是一个没有任何进一步引用的空数组。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接