2013-03-27 67 views
0

嗨,我是PHP新手,有以下問題。我寫了下面的代碼將數據添加到數組中,現在我需要查看添加的數據,請告訴我如何執行此操作。來自數組對象的GEt數據

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

你所說的「看到添加的數據」意味着檢索$items陣列? – Uby 2013-03-27 11:28:35

回答

0

由於$items是私有財產,你將需要在ShoppingCart類創建一個新的方法

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

,然後通過調用新的方法

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

var_dump($items);