【发布时间】:2016-11-12 01:19:18
【问题描述】:
我有一个带有以下代码的“game.php”:
<?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);
...
和一个带有以下代码的“database.php”:
<?php
include("constants.php");
class MySQLDB {
... constructor etc
function getUserInfosByGameID($gameid) { }
}
// Create database connection
global $database;
$database = new MySQLDB();
现在在创建新游戏对象时会抛出错误
“变量 $database 未在 game.php 第 12 行定义”
即使在“api.php”中它的工作方式是这样的:
<?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);
我做错了什么?我也尝试过在没有全局的情况下定义 $database,它也适用于“api.php”。
【问题讨论】:
-
你正在使用 include("database.php");在 game.php 和 include("include/database.php");在 api.php 中。你确定你的路径是正确的?
-
因为对象 MySQLDB 是另一个文件。根据你的代码结构,在声明全局变量之前先加载对象
-
查理鱼,是的,路径是正确的,game.php 和 database.php 在子文件夹“include”中
标签: php variables include undefined