PHP 对象,如数组

2022-08-30 15:02:17

我需要能够像这样设置我的对象:

$obj->foo = 'bar';

然后我需要像这样使用它作为数组:

if($obj['foo'] == 'bar'){
  //more code here
}

答案 1

只需添加到您的类并添加所需的方法:implements ArrayAccess

  • 公共函数偏移存在($offset)
  • 公共函数偏移量获取($offset)
  • 公共函数偏移集($offset, $value)
  • 公共函数偏移量Unset($offset)

查看 http://php.net/manual/en/class.arrayaccess.php


答案 2

尝试扩展数组对象

你还需要实现一个魔术方法,正如Valentin Golev所提到的。__get

您的类需要如下所示:

Class myClass extends ArrayObject {
    // class property definitions...
    public function __construct()
    {
        //Do Stuff
    }

    public function __get($n) { return $this[$n]; }

    // Other methods
}