【发布时间】:2021-09-22 03:21:56
【问题描述】:
我得到 array_key_exists() 期望参数 2 是数组,给定 null
在下面的代码中。我知道这是因为$this->items;为空,但我不确定如何修复它。
警告:array_key_exists() 期望参数 2 为数组,给定为空
public function __construct($cart = null)
{
if ($cart) {
$this->items = $cart->items;
$this->totalPrice = $cart->totalPrice;
$this->totalQty = $cart->totalQty;
} else {
$this->items = [];
$this->totalQty = 0;
$this->totalPrice = 0;
}
}
public function add($product)
{
$item = [
'id' => $product->id,
'name' => $product->name,
'price' => $product->price,
'qty' => 0,
'image' => $product->image
];
if (!array_key_exists($product->id, $this->items)) {
$this->items[$product->id] = $item;
$this->totalQty += 1;
$this->totalPrice += $product->price;
} else {
$this->totalQty += 1;
$this->totalPrice += $product->price;
}
$this->items[$product->id]['qty'] += 1;
}
【问题讨论】: