2

Im making a class in php, but Im having some problems with one of the class variables. I declare a private variable, then in the constructor set it. However, later in the class I have a method that uses that variable. The variable in this case is an array. However, the method says the array is blank, but when I check it in the constructor, it all works out fine. So really the question is, why does my array clear, or seem to clear, after the constructor?

<?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];
    }
}

The array is pulled in from another file because the array contains a lot of text. Didn't want to mash up this file with a huge array declared in the constructor. The scrolling would be tremendous. Any explanation would be nice, I like to understand my problems, not just fix em'.

1 Answer 1

1

You have a typo:

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

Moreover, in your case, include is better than require_once.

If you want to go deeper, you could rewrite $gamearray assignment like this:

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

// gamearray.php
return array(
    // Your data here
);
Sign up to request clarification or add additional context in comments.

1 Comment

Should have gone to bed and relooked at it so I would feel less stupid, oh well thanks a lot! And I learned the include thing too, so thanks a lot!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.