从数组对象中获取数据


GEt data from array object

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

谢谢

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

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

然后通过调用新方法

检索$items数组
$objectname = new ShoppingCart();
$items = $objectname->getItems();
var_dump($items);