来自数组对象的GEt数据

时间:2013-03-27 11:12:50

标签: php

您好我是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));

由于

1 个答案:

答案 0 :(得分:0)

由于$items是私有属性,您需要在ShoppingCart

上创建一个新方法
public function getItems()
{
    return $this->items;
}

然后通过调用新方法

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

var_dump($items);