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
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
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);
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 alsoarray()
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;
-
Thanks! Would you please help me on the second one that I've added?tillda– tillda2010年12月12日 16:13:35 +00:00Commented Dec 12, 2010 at 16:13
-
"regardless of whether it is empty or not" He's testing
is_array()
BoltClock– BoltClock2010年12月12日 16:19:28 +00:00Commented 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.casablanca– casablanca2010年12月12日 16:23:03 +00:00Commented Dec 12, 2010 at 16:23
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..