I am trying to create a collection of Item objects and display them on the screen though an object oriented programming style. I have two classes called LineItem and ObjectCollection. LineItem class holds each item object and ObjectCollection holds the data of collection of all the lineitems. Following code shows my LineItem class and the ObjectCollection class.
class LineItem {
private $item;
private $quantity;
public function __construct($item, $quantity) {
$this->item = $item;
$this->quantity = $quantity;
}
public function __toString() {
return "Item = ".$this->item." : Quantity = "
.$this->quantity;
}
public function setQuantity($quantity) {
$this->quantity = $quantity ;
}
public function getQuantity(){
return $this->quantity;
}
public function changeQuantity($value){
$this->quantity += $value;
}
public function getItem(){
return $this->item;
}
}
ObjectCollection:
class ObjectCollection {
//This is an array to hold line items
private $line_items_array ;
private $lineCounter; //Count the number of line items
public function __construct() {
//Create an array object to hold line items
$this->line_items_array = array();
$this->lineCounter = 0;
}
// This will add a new line object to line items array
public function addLineItem($line_item) {
$this->lineCounter++;
$this->line_items_array[] = $line_item;
}
public function getLineCount(){
return $lineCounter;
//return $this->lineCounter;
}
public function getLineItem(){
return $this->line_items_array;
//return $line_items_array;
}
}
Then I added further code to add 2 new items to the LineItem. At the same time, I added those results into my object collection.
$ca = new ObjectCollection();
$item1 = new Item("1",3.45);
$item1->setDescription("Description for Item 1");
$item1->setImage("Image1");
$lineitem1 = new LineItem($item1, 5);
$item2 = new Item("2",5.31);
$item2->setDescription("Description for Item 2");
$item2->setImage("Image2");
$lineitem2 = new LineItem($item2, 8);
$ca->addLineItem($lineitem1);
$ca->addLineItem($lineitem2);
When I try to display each line time separately by typing,
print $lineitem1;
It displays the correct result.
However, if I try to display items in the ObjectCollection class, it does not display any result on the screen.
This is the code that I am using to display my Object Collection;
for ($i = 0; $i < $ca->getLineCount(); $i++) {
$li = $ca->getLineItem($i);
$item = $li->getItem();
print $i.")Description:" . $item->getDescription() . ",
Price: ". $item->getPrice() . ", Quantity:" . $li->getQuantity() . "<br />";
}
What alterations should I make to my code so I can display my collection of objects?