Page 1 of 1

Need help with ArrayAccess conundrum

Posted: Thu May 14, 2009 3:37 pm
by ornerybits
okay so I've got an object implementing ArrayAccess like so:

Code: Select all

 
class Foo implements ArrayAccess{
    private $data;
    public function offsetGet($var) {
        return $this->data[$var];
    }   
    public function offsetSet($var, $value) {
        $this->data[$var] = $value;
    }   
 
    public function offsetExists($var) {
        return isset($this->data[$var]);
    }   
 
    public function offsetUnset($var) {
        unset($this->data[$var]);
    }   
}
 
... and theeeeeen..... when I run the following code...

Code: Select all

 
$foo = new Foo();
$foo['stinky'] = 'weaselteats';
$ref =& $foo['stinky'];
 
... i get the error:
Fatal error: Objects used as arrays in post/pre increment/decrement must return values by reference in foo.php.

Soooooooooo.... i tried changing the method definition of Foo::offsetGet() to return a reference like so...

Code: Select all

 
...
    public function &offsetGet($var){
        return $this->data[$var];
    }
...
 
.... buuuuuuuuuuuut... this conflicts with the definition of ArrayAccess::offsetGet, which does not return a reference, and i end up with this error:
Fatal error: Declaration of Foo::offsetGet() must be compatible with that of ArrayAccess::offsetGet() in foo.php

I can get both errors to go away by not attempting to assign the reference in the implementation like so...

Code: Select all

 
$ref = $foo['stinky'];
// no errors - but this is not what I want
 
I guess I don't know why PHP is throwing the first error. I don't understand why PHP is expecting a reference and a reference only. Any insight would be good. I've been surfing for this answer all morning.

Re: Need help with ArrayAccess conundrum

Posted: Thu May 14, 2009 3:49 pm
by crazycoders
You can't do this because you are asking to return the reference to something that is a function. So to be able to do that, you'd need to always return the information as a reference but you already have tried that.

My next question is simple, why use references to that? You need to update the value later? Is this always your plan, if so, try to send the reference like this:

Code: Select all

public function offsetGet($var) {
return &$this->data[$var];
}
I don't know if it'll work but it actually could work...
Don't forget to remove the =& and only use = now that its returning the ref!

Re: Need help with ArrayAccess conundrum

Posted: Thu May 14, 2009 4:03 pm
by ornerybits
can't do..

Code: Select all

 
public function offsetGet($var){
    return &$this->data[$var];
}
 
... results in...
'Parse error: syntax error, unexpected '&' in foo.php'

I guess I should mention I'm using PHP 5.2

I did find this though (after Googling the the error message, doi), http://bugs.php.net/bug.php?id=34783. Sounds like a losing battle. But I agree with the guy that disagrees with the other guy that says it's 'unsolvable'. Baloney.