PHP:如何遍历类的所有对象


PHP: how to iterate through all objects of a class?

我有一个代码,其中数组包含对象,其中包含对象,例如:

<?php
class person {
    public $name;
    public $foods=array();
}
class food {
    public $foodnames=array() ;
}
$peoplearray[$name] = new person;
$peoplearray[$name]->name = 'john' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'ice cream' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'banana' ;
$peoplearray[$name] = new person;
$peoplearray[$name]->name = 'julie' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'chocolate' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'coffee' ;
$peoplearray[$name]->foods[$key] = new food;
$peoplearray[$name]->foods[$key]->foodnames[$key] = 'rice' ;
?>

现在我也需要遍历类food中的所有对象,以便获取它们的属性。有人知道最有效的方法吗?

在类food中声明一个静态属性,并在构造时将您的food对象放入其中:

class food {
  public static $collection = array();
  // other properties ...
  public function __construct() {
    // Stuff
    self::$collection[] = $this;
  }
}
// Create foo objects
$f = new food();
// Iterate
foreach(food::$collection as $foodobj) {
  // Stuff
}