php - 为什么 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。
解决方案
$this->items[]=$newItem;
$this->count++;
推荐阅读
- java - 如何在 android 的循环进度条中将变量作为 setIndicatorSize 的参数?
- react-native - 我们没有找到使用 mesibo SDK 在本机反应中创建新 UI 的代码
- python - 使用从 python 文件到 kv 文件的变量的 kivy 错误
- r - 如何在 R 中跨多个数据帧沿单列迭代函数
- django - 信号和任务文件未在 django celery 中连接
- python-3.x - python帮助从文件中提取信息
- python - 是否可以将所有相同格式的文件读入ffmpeg中的一个命令?
- bootstrap-4 - 我的导航栏折叠延迟在 pagespeed 洞察中添加到 CLS。怎么提高?
- git - 如何重新设置分叉的本地分支?
- amazon-web-services - Lex V2 Bot 执行导致 500 个内部错误