PHP有许多具有一个Class的对象

时间:2011-11-30 01:56:16

标签: php oop

我是PHP和OOP技术的新手。

所以创建像这样的对象没问题:

$member1 = new Member('person 1');

但是有没有办法返回一堆对象。这样我可以遍历它们并将它们放入DOM中?

2 个答案:

答案 0 :(得分:1)

class Example
{
    public function getPeople()
    {
        $objs = array();
        for($i = 0; $i < 10; $i++)
        {
            $obj[] = new Person('Person ' . ($i + 1));
        }
        return $objs; // returning an array of Person objects
    }
}
$example = new Example();
foreach($example->getPeople() as $person)
{
    // Do something with $person
}

答案 1 :(得分:0)

为了获取对象,一种可能的方法是使用数组: -

$members = new members( array(...));
// you can assess any member via $members->members[$some_id] 

// class to return list of members
class members ()
{
  public $members = array();
  public function __construct( array $ids)
  {
    foreach ($id as $id)
    {
      $this->members[$id] = new Member($id);
    }
  }
}

class member()
{
  public function __construct($id)
  {
    // any other thing you want to do
  }
}