【问题标题】:PHP Class: Array deinitialized after constructor?PHP类:构造函数后数组取消初始化?
【发布时间】:2012-07-11 06:16:21
【问题描述】:

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

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

【问题讨论】:

    标签: php arrays class constructor initialization


    【解决方案1】:

    你有一个错字:

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

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

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

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

    【讨论】:

    • 应该去睡觉再看一遍,这样我就不会那么愚蠢了,哦,非常感谢!我也学到了包含的东西,非常感谢!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 1970-01-01
    • 2013-12-30
    • 2011-05-02
    相关资源
    最近更新 更多