您好我是PHP的新手并且遇到问题。我写下面的代码将数据添加到数组中,现在我需要查看添加的数据,请告诉我该怎么做。
class ShoppingCart
{
private $items = array();
private $n_items = 0;
function addItem( Item $item )
{
$this->items[] = $item;
$this->n_items = $this->n_items + 1;
//print_r (array_values($this->items));
echo "item $this->items added sussesfully";
}
}
和
class Item {
protected $name;
protected $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getName() {
echo "item is $this->name";
return $this->name;
}
public function getPrice() {
return $this->price;
}
}
和
require_once('AddingMachine.php');
require_once('item.php');
//$arrayofnumbers = array(100,200);
$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));
由于
答案 0 :(得分:0)
由于$items
是私有属性,您需要在ShoppingCart
类
public function getItems()
{
return $this->items;
}
然后通过调用新方法
来检索$items
数组
$objectname = new ShoppingCart();
$items = $objectname->getItems();
var_dump($items);