What is a correct way to use
array_splicein 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
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;
3 Comments
is_array()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..