Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP pass array by reference

  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

like image 769
tillda Avatar asked May 26 '26 00:05

tillda


2 Answers

  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;
    
like image 73
casablanca Avatar answered May 28 '26 15:05

casablanca


Why would you return a reference to an array, especially in the code you provided:

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

When that function is would work, it could return a reference to an empty array, I could do with it what I want and change it as much as I'd like, but it wouldn't have any effect, because it was just an empty array without any further reference at all..

like image 27
GolezTrol Avatar answered May 28 '26 15:05

GolezTrol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!