使用集合类PHP输出数据

时间:2018-01-07 16:18:19

标签: php collections

我创建了一个集合类,然后是一个类汽车。我正在添加汽车类的实例也是集合类。在我的班车中,我可以为每辆车添加描述,最高速度等。我希望能够遍历所有汽车并输出描述和最高速度。很抱歉很多代码我希望你能理解我想要实现的目标。我在底部代码/类中添加了一个注释,我希望输出这些内容。

收集课程:

<?php 
 class ObjectCollection  
{  
    //This is an array to hold line items
    private $items_array ;

    private $itemCounter; //Count the number of items

    public function __construct() {
        //Create an array object to hold line items
        $this->items_array = array();
        $this->itemCounter=0; 
     }

    public function getItemCount(){
        return $this->itemCounter;
    }  


    // This will add a new line object to line items array
    public function addItem($item) {
       $this->itemCounter++;
       $this->items_array[] = $item;
    }

}
?>

我的车类:     

class car {
  private $id;
  private $description;
  private $topspeed;
  private $price;

  public function __construct($id, $price) {
       $this->id = $id;
       $this->price = $price;
  }

  public function setDescription($description) {
            $this->description = $description ;
  }

  public function getDescription() {
      return $this->description ;
  }

  public function setTopspeed($topspeed) {
            $this->topspeed = $topspeed;
 }

public function getTopspeed() {
      return $this->topspeed ;
 }

 //other methods here

} //End of class

?>

CLASS我正在循环ObjectCollection

 $car = new car("1",400);
 $car2 = new car("2",4400);

 $car->setDescription("A really fast car ");
 $car2->setDescription("A really slow car ");



 $ObjColl = new ObjectCollection();
 $ObjColl->addItem($car1);
 $ObjColl->addItem($car2);



 for($i = 0;$ObjColl->getItemCount();$i++){
   //CODE NEED TO BE ADDED TO OUTPUT TOPSPEED AND DESCRIPTION ECT????
}

1 个答案:

答案 0 :(得分:0)

首先将以下方法添加到ObjectCollection类以访问items数组:

public function getItems(){
    return $this->items_array;
}

然后你就可以像下面的代码一样循环:

foreach ($ObjColl->getItems() as $item){
    if (is_a($item, 'car')){
        echo $item->getDescription();
    }
}