PHP object like array

后端 未结 9 559
臣服心动
臣服心动 2020-12-10 00:53

I need to be able to set my object like this:

$obj->foo = \'bar\';

then I need to use it as an array like that:

if($obj[\'f         


        
9条回答
  •  死守一世寂寞
    2020-12-10 01:48

    ArrayObject implements the ArrayAccess interface (and some more). Using the ARRAY_AS_PROPS flag it provides the functionality you're looking for.

    $obj = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS);
    $obj->foo = 'bar';
    echo $obj['foo'];
    

    Alternatively you can implement the ArrayAccess interface in one of your own classes:

    class Foo implements ArrayAccess {
      public function offsetExists($offset) {
        return isset($this->$offset);
      }
    
      public function offsetGet($offset) {
        return $this->$offset;
      }
    
      public function offsetSet($offset , $value) {
        $this->$offset = $value;
      }
    
      public function offsetUnset($offset) {
        unset($this->$offset);
      }
    }
    
    $obj = new Foo;
    $obj->foo = 'bar';
    echo $obj['foo'];
    

提交回复
热议问题