Возможность расширения класса без функциональных недостатков
Вы также можете использовать ArrayAccess для доступа к одному свойству массива в вашем классе и оставить доступ к другим свойствам способом ООП. И все же он будет работать так, как вы просили.
class Foo implements \ArrayAccess
{
/**
* mixed[] now you can access this array using your object
* like a normal array Foo['something'] = 'blablabla'; echo Foo['something']; ... and so on
* other properties will remain accessed as normal: $Foo->getName();
*/
private myArrayOptions = [];
private $name = 'lala';
...
public function offsetExists($offset)
{
return isset($this->myArrayOptions[$offset]);
}
public function offsetGet($offset)
{
if ($this->offsetExists($offset)) {
return $this->myArrayOptions[$offset];
}
return null; // or throw the exception;
}
public function offsetSet($offset, $value)
{
$this->myArrayOptions[$offset] = $value;
}
public function offsetUnset($offset)
{
unset($this->myArrayOptions[$offset]);
}
public function getName()
{
return $this->name;
}
public function __set($offset, $value){
$this->myArrayOptions[$offset] = $value;
}
...
}
Выше будет работать, как вы ожидали.
$obj->foo = 'bar';
if($obj['foo'] == 'bar'){
echo "WoWo";
}
Также обратите внимание, что Foo ['name'] ! == Foo-> getName ()
это две разные переменные