像数组一样的 PHP 对象 [英] PHP object like array
本文介绍了像数组一样的 PHP 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要能够像这样设置我的对象:
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['foo'] == 'bar'){
//more code here
}
推荐答案
尝试扩展 ArrayObject
您还需要实现一个 __get
魔法方法正如瓦伦丁·戈列夫提到的那样.
You'll also need to implement a __get
Magic Method as Valentin Golev mentioned.
你的类需要看起来像这样:
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
}
这篇关于像数组一样的 PHP 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文