0

我有以下数组结果

Array ( [0] => Item Object ( [name:protected] => My Super Cool Toy [price:protected] =>      10.99 ) )

我需要[name:protected] => My Super Cool Toy从这个数组中获取。

请告诉我如何获得它,

我将在下面粘贴我的课程

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($this->items);

}
}

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));

 $obname = new Item($items,44);
$obname->getName();

谢谢

4

2 回答 2

0

如果我猜对了,你在 ShoppingCart 类的 addItem 方法中得到了这个数组,所以要访问它,你只需使用相应的 getter 方法,例如:

$this->items[0]->getName();
于 2013-03-27T13:05:48.517 回答
0

你可以试试 :

$objectname = new ShoppingCart();
$objectname->addItem(new Item('My Super Cool Toy', 10.99));

foreach ( $objectname->getItems() as $item ) {
    echo $item->getName(), PHP_EOL;
}

修改类

class ShoppingCart {
    private $items = array();
    private $n_items = 0;

    function addItem(Item $item) {
        $this->items[] = $item;
        $this->n_items = $this->n_items + 1;
    }

    function getItems($n = null) {
        return $n === null ? $this->items : (isset($this->items[$n]) ?  : $this->items[$n]);
    }
}
于 2013-03-27T13:15:18.967 回答