我试图理解这个对象,但我无法弄清楚一个简单的事实。如果count方法显示公共属性,则结果是传递的数组中的键数。在关联数组的情况下,当我尝试访问像公共属性的密钥时找不到。也许我误解了界面。
//example
$currentDate = getdate();
//applying print_r() we can see the content
$objectDate = new ArrayObject();
//verifying the public properties- result is 11
$objectDate->count();
//but can't access keys like public properties
$objectDate->hours;
答案 0 :(得分:3)
您可以通过将->
标志传递给ArrayObject
构造函数来将数组条目作为属性(ArrayObject::ARRAY_AS_PROPS
)进行访问:
//example
$currentDate = getdate();
print_r($currentDate);
// create ArrayObject from array, make entries accessible as properties (read and write).
$objectDate = new ArrayObject($currentDate, ArrayObject::ARRAY_AS_PROPS);
// verifying the public methods - result is 11
print_r($objectDate->count());
print "\n";
// accessing entries like public properties
print_r($objectDate->hours);
答案 1 :(得分:2)
这样的类实现了ArrayAccess
接口,所以你可以写:
$objectDate['hours']
使用括号表示法,但不能使用箭头[->
]一个。