0

嗨,我是 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));

谢谢

4

1 回答 1

0

由于$items是私有属性,因此您需要在ShoppingCart类上创建一个新方法

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

$items然后通过调用新方法检索数组

$objectname = new ShoppingCart();
$items = $objectname->getItems();

var_dump($items);
于 2013-03-27T11:29:02.277 回答