ThexBasic ThexBasic - 4 months ago 11
PHP Question

PHP "global" variable not accessible in __construct

I have an "game.php" with the following code:

<?php
include("database.php");

class Game {
var $gameinfo;
var $gameid;
var $players;

function __construct($gameinfo) {
$this->gameinfo = $gameinfo;
$this->gameid = $gameinfo["gameid"];

$this->players = $database->getUserInfosByGameID($this->gameid);
...


and an "database.php" with the following code:

<?php

include("constants.php");

class MySQLDB {
... constructor etc
function getUserInfosByGameID($gameid) { }
}
// Create database connection
global $database;
$database = new MySQLDB();


now when creating a new game-object it throws the error


"variable $database not defined in game.php row 12"


even though in "api.php" it works like this:

<?php
// check for POST method
if($_SERVER["REQUEST_METHOD"] != "POST")
die();

include("include/database.php");
// get json data
$stream_data = file_get_contents('php://input');
$json = json_decode($stream_data) or die("{valid=false}");

// if session in $json try to get user object from DB
if(isset($json->session))
$sessionuser = $database->confirmUserSession($json->session);


what am I doing wrong? I've also tried defining $database without global, which also works in "api.php".

Answer

You should declare global $database in the constructor as well so the method has access to the variable.

function __construct($gameinfo) {
    global $database;
    $this->gameinfo = $gameinfo;
    $this->gameid = $gameinfo["gameid"];

    $this->players = $database->getUserInfosByGameID($this->gameid);

EDIT

Here is the official docs about this topic.

Comments