Magic methods don't work inside ArrayObjects?
-
22-02-2021 - |
Question
I ran accross a problem with my code that I could not explain. The only thing I can think of is that magic methods just don't work inside of ArrayObjects. For instance, given the following class:
class foo extends ArrayObject {
public $bar = '@@@';
public function __construct() {
parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
}
public function __get($prop) {
return '@@@';
}
}
The following lines give me an error "Notice: Undefined index: test ..."
$foo = new foo();
echo $foo->test;
Yet these lines work fine:
$foo = new foo();
echo $foo->bar;
Am I crazy or is this a known issue?
La solution
The "magic" function you're looking for is called offsetGet
Docs, not __get
:
class foo extends ArrayObject {
public $bar = '@@@';
public function __construct() {
parent::__construct(array(), ArrayObject::ARRAY_AS_PROPS);
}
public function offsetGet($prop)
{
if (!parent::offsetExists($prop))
return '@@@';
return parent::offsetGet($prop);
}
}
$foo = new foo();
echo $foo->test; # @@@
I don't know it for sure, but __get
is not available as you're extending from an internal class that is somehow blocking it.
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow