首页 > 解决方案 > 为什么 PHP 将我的数组识别为标量值?

问题描述

我在网站上使用 ShoppingCart 对象来存储有关客户添加到其个人购物车中的菜单项的信息时遇到问题。

我对 PHP 比较陌生,但是用 Java 编码已经接近 10 年了,所以我对面向对象编程的工作原理有一个深刻的理解。

在我的购物车中,我有两个实例变量,声明如下:

public $items;
public $count;

public function __construct(){
    $items=array();
    $count=0;
}

其中 items 应该是一个数组来存储 CartItem 对象。

我将一个项目插入到数组中,如下所示:

public function addToCart($item_id, $quantity){
    $newItem=new CartItem();
    $newItem->setID($item_id);
    $newItem->setQuant($quantity);
    $this->$items[]=$newItem;
    $this->$count++;
}

现在,每当我尝试运行时,都会收到以下警告:

Warning: Cannot use a scalar value as an array

警告指向线的位置

$this->$items[]=$newItem;

我在完全理解这个警告和理解我做错了什么方面遇到了一些麻烦。我不确定这个警告到底在告诉我什么,但我觉得它正在将 $items 识别为标量值,因为每当我尝试回显它时,我得到的打印值是 0 而不是 Array。

标签: phphtmlarrays

解决方案


$this->items[]=$newItem;
$this->count++;

推荐阅读