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 Answers 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;
    
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! Would you please help me on the second one that I've added?
"regardless of whether it is empty or not" He's testing is_array()
@BoltClock: I noticed that, but I'm guessing that he is likely testing if it's empty. I'll wait for the OP's response.
1

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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.