【发布时间】:2016-06-12 11:41:23
【问题描述】:
使用 foreach 进行对象迭代很容易:
foreach ($item->attributes as $attribute) {
// echo $attribute->name;
}
.. 但我想知道是否可以用for 代替:
for ($j=0; $j < count($item->attributes); $j++) {
// echo $item->attributes->$j->$name ?
}
虽然我可以在 foreach 之外创建一个计数器并增加它,但只是想知道 for 是否适用于对象。
作为参考,我正在使用的对象看起来像 this。
【问题讨论】:
-
是的,它会起作用,但为什么不自己尝试呢?
-
来自 pastebin,
galleryInfoContainer的孩子具有私有访问标识符,您无法在课堂外访问它们。 -
@rjdown 谢谢你,但显然所有的例子都使用
foreach,那里没有提到for。 -
@kamalpal 也许,但我可以使用
foreach访问它,没有任何问题。