像数组一样的 PHP 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2007695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:39:14  来源:igfitidea点击:

PHP object like array

phparrays

提问by oxfletchox

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

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

$obj->foo = 'bar';

then after that is set i need the following to be true

然后在设置之后我需要以下内容为真

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

采纳答案by Valentin Golev

Try extending ArrayObject

尝试扩展ArrayObject

You'll also need to implement a __getMagic Methodas Valentin Golev mentioned.

您还需要实施Valentin Golev 提到的__get魔术方法

Your class will need to looks something like this:

你的类需要看起来像这样:

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

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

    // Other methods
}

回答by Gordon

Just add implements ArrayAccessto your class and add the required methods:

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

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

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

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

回答by VolkerK

ArrayObjectimplements the ArrayAccess interface (and some more). Using the ARRAY_AS_PROPSflag it provides the functionality you're looking for.

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

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

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

或者,您可以在自己的类之一中实现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'];

回答by Pascal MARTIN

You'll have to implement the ArrayAccessinterface to be able to do that -- which only means implementing a few (4 to be exact)simple methods :

您必须实现ArrayAccess接口才能做到这一点——这仅意味着实现几个(准确地说是 4 个)简单方法:

There is a full example on the manual's page I pointed to ;-)

我指向的手册页面上有一个完整的示例;-)

回答by Adam Hopkinson

You're mixing objects and arrays. You can create and access an object like so:

您正在混合对象和数组。您可以像这样创建和访问一个对象:

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

if($obj->foo == 'bar'){
// true
}

and an array like so:

和一个像这样的数组:

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

if($obj['foo'] == 'bar'){
// true
}

You can define a class and add implements ArrayAccess if you want to access your class as both an array and a class.

如果您想将您的类作为数组和类访问,您可以定义一个类并添加实现 ArrayAccess。

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

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

回答by Ifan Iqbal

You can access PHP object as PHP array, but in different ways. Try this:

您可以将 PHP 对象作为 PHP 数组访问,但方式不同。尝试这个:

$obj->{'foo'}

That is similar with accessing array like this:

这与像这样访问数组类似:

$arr['foo']

You can also do this:

你也可以这样做:

$propertyName = 'foo';
$obj->$propertyName; // same like first example

回答by soulmerge

Your object must implement the ArrayAccessinterface, then PHP will allow you to use the square brackets like that.

您的对象必须实现该ArrayAccess接口,然后 PHP 将允许您使用这样的方括号。

回答by DevWL

Enhance Class capability with no functionality drawbacks

在没有功能缺陷的情况下增强类能力

You can also use ArrayAccess to access a single array property in your class and leave other properties being accessed in OOP way. Yet still it will work as you requested.

您还可以使用 ArrayAccess 访问类中的单个数组属性,并以 OOP 方式访问其他属性。然而它仍然会按照你的要求工作。

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;
    }

    ...

}

The above will work as you expected.

以上将按您的预期工作。

$obj->foo = 'bar';
if($obj['foo'] == 'bar'){
    echo "WoWo";
}

Also note that Foo['name'] !==Foo->getName() those a two different variables

还要注意 Foo['name'] !==Foo->getName() 那两个不同的变量

回答by ceejayoz

You could also cast the object as an array:

您还可以将对象转换为数组:

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