2

我在 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];
    }
}

该数组是从另一个文件中提取的,因为该数组包含大量文本。不想用构造函数中声明的巨大数组来混搭这个文件。滚动将是巨大的。任何解释都会很好,我想了解我的问题,而不仅仅是解决问题。

4

1 回答 1

1

你有一个错字:

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

此外,在您的情况下,include优于require_once.

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

// Module.php 
$this->gamearray = include LIB_DIR.'arrays/gamearray.php';

// gamearray.php
return array(
    // Your data here
);
于 2012-07-11T15:21:13.023 回答