PHP类:数组在构造函数之后被取消初始化


PHP Class: Array deinitialized after constructor?

我在php中创建了一个类,但其中一个类变量存在一些问题。我声明了一个私有变量,然后在构造函数中设置它。但是,稍后在类中我有一个使用该变量的方法。本例中的变量是一个数组。然而,该方法表示数组为空,但当我在构造函数中检查它时,一切都很好。所以真正的问题是,为什么我的数组在构造函数之后被清除,或者看起来被清除了?

<?php
class Module extends RestModule {
    private $game;
    private $gamearray;
    public function __construct() {
        require_once (LIB_DIR."arrays/gamearray.php");
        $this->gamearray = $gamesarray;
        $this->game = new Game();
        $this->logger = Logger::getLogger(__CLASS__);
        $this->registerMethod('add', array(Rest::AUTH_PUBLIC, Rest::AUTH_USER, Rest::AUTH_ADMIN), true);
        $this->registerMethod('formSelect', array(Rest::AUTH_PUBLIC, Rest::AUTH_USER, Rest::AUTH_ADMIN), false);
    }
    public function add(){
        $game = Utility::post('game');        
    }
    public function formSelect(){
        $gamename = Utility::get('game');
        $this->$gamearray[$gamename];
    }
}

该数组是从另一个文件中拉入的,因为该数组包含大量文本。我不想把这个文件和构造函数中声明的一个巨大数组混在一起。滚动将是巨大的。任何解释都很好,我喜欢理解我的问题,而不仅仅是解决它们。

您有一个打字错误:

public function formSelect(){
    $gamename = Utility::get('game');
    $this->gamearray[$gamename]; // Remove the $ before gamearray
}

此外,在您的情况下,includerequire_once更好。

如果你想更深入,你可以像这样重写$gamearray赋值:

// Module.php 
$this->gamearray = include LIB_DIR.'arrays/gamearray.php';
// gamearray.php
return array(
    // Your data here
);