首页 > 解决方案 > 数组在类中返回 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

标签: php

解决方案


您似乎对变量范围有点困惑。中还有一个错误$$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)
}
*/

推荐阅读