Richard
Richard

Reputation: 4546

is this considered a bug in php offsetget method

example with an object that extends an object that implements ArrayAccess

if I try to access a variable in an object way both _get and offsetget are called, but if I access it array like only offsetget is called

I don't seem to have a problem (I get the value from _get returned, if there is one) ,but the offsetget method could potentionally mess things up

Anyone experience with this

class Container implements ArrayAccess {

    public function offsetGet($key)
    {
      $this->t .= "call magic offsetGet with $key<br>";
      return $this->make($key);
    }
}
class Application extends Container{
   protected $t="";
    public function __get($key)
    {        
        $this->t .= "call magic _get with $key<br>";
        return $this[$key];
    }
}


$e = $app->t;
// $e = $app['b'];
// echo $app->t;
var_dump($e);

Upvotes: 0

Views: 126

Answers (2)

IMSoP
IMSoP

Reputation: 97898

As deceze points out, this is not PHP calling both magic methods at the same time, they are both explicitly called in your code:

  1. You access a non-existent property, say $app->foo
  2. This will call Application::__get with $key = 'foo'
  3. That includes the line $this[$key], which will resolve to $this['foo']
  4. $this is an object being accessed as an array, so causes a call to Container::offsetGet with $key='foo'

If you just access $app['foo'] directly, Application::__get is never called, because you are jumping straight to step 4.

Similarly, if you comment out the return $this[$key] line in Application::__get, there will be no call to Container::offsetGet, because that is the line that is invoking the ArrayAccess magic.

Upvotes: 1

Jack
Jack

Reputation: 1606

As manual states:

__get() is utilized for reading data from inaccessible properties. 

Issuing the following will create a public properties named 'b':

$app->b ="hh";

From now on if you access $app->b the __get() method is no longer called

Upvotes: 0

Related Questions