PHP object like array

后端 未结 9 551
臣服心动
臣服心动 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:42

    Just add implements ArrayAccess to your class and add the required methods:

    • public function offsetExists($offset)
    • public function offsetGet($offset)
    • public function offsetSet($offset, $value)
    • public function offsetUnset($offset)

    See http://php.net/manual/en/class.arrayaccess.php

    0 讨论(0)
  • 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'];
    
    0 讨论(0)
  • 2020-12-10 01:50

    You could also cast the object as an array:

    if((array)$obj['foo'] == 'bar'){
      //more code here
    }
    
    0 讨论(0)
提交回复
热议问题