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

hakre
199k55 gold badges453 silver badges865 bronze badges
asked Dec 12, 2010 at 16:05

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;
    
BoltClock
727k165 gold badges1.4k silver badges1.4k bronze badges
answered Dec 12, 2010 at 16:07
3
  • Thanks! Would you please help me on the second one that I've added? Commented Dec 12, 2010 at 16:13
  • "regardless of whether it is empty or not" He's testing is_array() Commented Dec 12, 2010 at 16:19
  • @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. Commented Dec 12, 2010 at 16:23
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..

answered Dec 12, 2010 at 16:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.