Reputation: 4546
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
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:
$app->foo
Application::__get
with $key = 'foo'
$this[$key]
, which will resolve to $this['foo']
$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
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