PHP object like array

2020-02-10 01:53发布

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
}

标签: php arrays
9条回答
Juvenile、少年°
2楼-- · 2020-02-10 02:21

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

查看更多
家丑人穷心不美
3楼-- · 2020-02-10 02:29

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

$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
查看更多
Explosion°爆炸
4楼-- · 2020-02-10 02:33

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

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

查看更多
登录 后发表回答