我在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];
}
}
该数组是从另一个文件中提取的,因为该数组包含大量文本。不想使用构造函数中声明的巨大数组来混搭此文件。滚动将是巨大的。任何解释都会很好,我喜欢理解我的问题,而不仅仅是修复它们。
答案 0 :(得分: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
);