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

时间:2012-07-23 13:56:45

标签: php class object

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

<?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' ;
?>

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

1 个答案:

答案 0 :(得分:2)

在类食物中声明一个静态属性,并在构造时将食物放入其中:

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
}