未定义的偏移量:第55行的1

I have the problem like the title says. I know what this problem means but i dont know how to solve it in my specific case so i nedd your help.

I have Item.php and Cart.php. In Item.php constructor is:

public function __construct($id, $price, $name) {
    $this->id=$id;
    $this->price=$price;
    $this->name=$name;
}

and in Cart.php constructor is:

public function __construct($items = array()) {
    if(empty($items)){
        $this->items=array();
                    $this->quantities=array();
    } else {
        foreach($items as $key => $value){
            $this->items[]=$value;
                            $this->quantities[$value]++;
                    }
    }

}

and function in Cart.php also is:

public function addItem(Item $item, $quantity = 1) {
        for($i=0; $i<$quantity; $i++){
            $this->items[]=$item;
            $this->quantities[$item->getId()]++;
        }

}

And the main code is:

$cart = new Cart();
$book = new Item(1, 59.99, 'PHP Cookbook');
$cart->addItem($book, 10);
foreach($cart->getItems() as $item) {
echo $item->getPrice(), " ", $item->getName(), " ", $cart->getQuantity($item), "<br>";
}

The bold line is Line:

$this->quantities[$item->getId()]++; 

in method addItem.

It seems to me like when i say: $book = new Item(1, 59.99, 'PHP Cookbook'); the php should find $id 1 but he doesnt. The weirdest thing is that the result is being displayed correctly on my screen.

You have never set quantities(1).

Replace your line

$this->quantities[$item->getId()]++;

by :

if(isset($this->quantities[$item->getId()]))
    $this->quantities($item->getId()]++;
else
    $this->quantities($item->getId()] = 1;