php - 数组在类中返回 NULL
问题描述
我正在尝试声明一个全局数组,但是在尝试检索它时它返回 NULL
游戏管理器.php
namespace TMSE;
use PDO;
class GamesManager extends Main {
protected $DB;
public $cards = array();
public function __construct() {
global $cards;
$this->$cards = array('2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9, 'T' => 10, 'J' => 10, 'Q' => 10, 'K' => 10, 'A' => 11);
var_dump($cards);
}
public function pullCard() {
global $cards;
var_dump($cards);
}
}
两个 var_dump 都返回 NULL
解决方案
您似乎对变量范围有点困惑。中还有一个错误$
。$this->$cards
虽然这是有效的语法,但它并没有达到您的预期。
请考虑以下内容以了解您的代码出了什么问题。请参阅最后的评论和输出以获取解释。
<?php
$cards = [4, 5, 6]; // Global scope
class GamesManager
{
public $cards = []; // Class scope
public function __construct()
{
$this->cards = [1, 2, 3]; // This will set the class variable $cards to [1, 2, 3];
var_dump($this->cards); // This will print the variable we've just set.
}
public function pullCard()
{
global $cards; // This refers to $cards defined at the top ([4, 5, 6]);
var_dump($this->cards); // This refers to the class variable named $cards
/*
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
*/
var_dump($cards); // This refers to the $cards 'imported' by the global statement at the top of this method.
/*
array(3) {
[0]=>
int(4)
[1]=>
int(5)
[2]=>
int(6)
}
*/
}
}
$gm = new GamesManager;
$gm->pullCard();
/*
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
array(3) {
[0]=>
int(4)
[1]=>
int(5)
[2]=>
int(6)
}
*/
推荐阅读
- bluetooth - 是否可以将数据写入 BLE 广播设备?
- python - 是否可以从文件中传递 python 行为命令行参数
- javascript - vue和react中的功能相同,但在react中不起作用
- javascript - JavaScript/浏览器中的事件处理
- python - 如何在 TF2 中构建具有容差的自定义精度指标?
- azure - 导入 Azure 数据工厂的 SharePoint 列表大小限制
- java - B4A 中的错误:java.lang.RuntimeException:应首先初始化对象(EditText)
- python - os.popen 奇怪的编解码器问题
- java - Selenium 无法切换到 iframe 端输入用户名-Java
- scala - 将 XML 列解析为多列并根据 Spark DataFrame 中的计数转置为行