【发布时间】:2015-12-28 18:48:14
【问题描述】:
我正在尝试创建 Item 对象的集合,并通过面向对象的编程风格将它们显示在屏幕上。我有两个名为 LineItem 和 ObjectCollection 的类。 LineItem 类保存每个项目对象,ObjectCollection 保存所有 lineitem 的集合数据。以下代码显示了我的 LineItem 类和 ObjectCollection 类。
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;
}
}
对象集合:
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;
}
}
然后我添加了更多代码以将 2 个新项目添加到 LineItem。同时,我将这些结果添加到我的对象集合中。
$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);
当我尝试通过键入分别显示每一行时间时,
print $lineitem1;
它显示正确的结果。
但是,如果我尝试在 ObjectCollection 类中显示项目,它不会在屏幕上显示任何结果。
这是我用来显示我的对象集合的代码;
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 />";
}
我应该对我的代码进行哪些更改才能显示我的对象集合?
【问题讨论】:
-
您应该启用错误报告。您应该有关于将数组作为对象访问的通知/警告。
-
创建对象集合的最佳方式是实现
IteratorAggreagate(php.net/manual/en/class.iteratoraggregate.php),这将允许您使用foreach、Countable(php.net/manual/en/class.countable.php),这将允许如果您想按索引访问集合,您可以使用count()和可能的ArrayAccess(php.net/manual/en/class.arrayaccess.php) 来计算集合。