【问题标题】:PHP "global" variable not accessible in __construct__construct 中无法访问 PHP“全局”变量
【发布时间】: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


【解决方案1】:

您还应该在构造函数中声明全局$database,以便该方法可以访问该变量。

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

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

编辑

这里是关于这个话题的官方docs

【讨论】:

  • 之所以有效,是因为类的方法是一个密封的环境。所以它只能访问类的属性或输入。如果要使用全局变量,则必须在方法中声明它,以便它具有可见性。关于这个话题你可以阅读官方docs
【解决方案2】:

将您的全局变量放在MySQLDB 之前,因为MySQLDB 类将查找$database

<?php

global $database;

include("constants.php");

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

【讨论】:

    猜你喜欢
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 2014-04-08
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多