PHP对象就像数组一样

oxf*_*hox 23 php arrays

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

$obj->foo = 'bar';
Run Code Online (Sandbox Code Playgroud)

然后在设置之后我需要以下是真的

if($obj['foo'] == 'bar'){
  //more code here
}
Run Code Online (Sandbox Code Playgroud)

Val*_*lev 17

尝试扩展ArrayObject

你还需要实现一种__get 魔术方法,正如Valentin Golev所提到的那样.

你的课程需要看起来像这样:

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

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

    // Other methods
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,现在你需要定义函数__get()和__set().例如,函数__get($ n){return $ this [$ n]; } (2认同)

Gor*_*don 17

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

  • 公共函数offsetExists($ offset)
  • 公共函数offsetGet($ offset)
  • public function offsetSet($ offset,$ value)
  • public function offsetUnset($ offset)

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


Vol*_*erK 15

ArrayObject实现了ArrayAccess接口(以及更多).使用ARRAY_AS_PROPS标志,它提供您正在寻找的功能.

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

或者,您可以在自己的类中实现ArrayAccess接口:

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'];
Run Code Online (Sandbox Code Playgroud)


Pas*_*TIN 9

你必须实现ArrayAccess接口才能做到这一点 - 这只意味着实现一些(准确的4个)简单方法:

在我指出的手册页面上有一个完整的例子;-)


Ada*_*son 9

你正在混合对象和数组.您可以创建和访问对象,如下所示:

$obj = new stdClass;
$obj->foo = 'bar';

if($obj->foo == 'bar'){
// true
}
Run Code Online (Sandbox Code Playgroud)

和这样的数组:

$obj = new Array();
$obj['foo'] = 'bar';

if($obj['foo'] == 'bar'){
// true
}
Run Code Online (Sandbox Code Playgroud)

如果要将类作为数组和类访问,则可以定义类并添加实现ArrayAccess.

http://www.php.net/manual/en/language.oop5.php


Ifa*_*bal 7

您可以以PHP数组的形式访问PHP对象,但方式不同.试试这个:

$obj->{'foo'}
Run Code Online (Sandbox Code Playgroud)

这与访问数组类似:

$arr['foo']
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

$propertyName = 'foo';
$obj->$propertyName; // same like first example
Run Code Online (Sandbox Code Playgroud)

  • Upvoting因为语法糖. (4认同)