【问题标题】:Possible PHP scope issue with file include?文件包含可能的 PHP 范围问题?
【发布时间】:2012-04-05 11:53:12
【问题描述】:

我目前正在重写我的一个旧 PHP 脚本,以便代码结构良好,以供将来更新。

我正在尝试做的一件事是创建一个配置文件 - 以便可以通过编辑一个文件轻松更改设置。

文件源代码:functions.php

function ConnectToDB() {

    //database configurations...
    $host = "localhost";
    $dbuser = "root";
    $dbpass = "";
    $tblname = "parents";

    $connection = mysql_connect($host,$dbuser,$dbpass);

    if (!$connection) {
        echo 'Could not connect to the database. Please contact the administrator for more information.';
    }

    // select the db
    $db_selected = mysql_select_db($tblname, $connection);

    if (!$db_selected) {
        echo 'Could not select the parents evening table. Please contact the administrator for more information.';
        return false;
    }else{
        return true;
    }

}

文件:config.php

<?php

//database configurations...
$host = "localhost";
$dbuser = "root";
$dbpass = "";
$tblname = "parents";

?>

这是我的新代码: 文件:functions.php

function ConnectToDB() {

    include('inc/config.php');

    global $host; //needed becuase the scope of the variable throws an error otherwise.
    global $dbuser; //needed becuase the scope of the variable throws an error otherwise.
    global $dbpass; //needed becuase the scope of the variable throws an error otherwise.
    global $tblname; //needed becuase the scope of the variable throws an error otherwise.

    $connection = mysql_connect($host,$dbuser,$dbpass);

    if (!$connection) {
        echo 'Could not connect to the database. Please contact the administrator for more information.';
    }

    // select the db
    $db_selected = mysql_select_db($tblname, $connection);

    if (!$db_selected) {
        echo 'Could not select the parents evening table. Please contact the administrator for more information.';
        return false;
    }else{
        return true;
    }

}

我的旧代码过去可以完美运行,但是现在我将变量更改为不同的文件,我的应用程序不断输出“无法选择父母的晚宴桌。请联系管理员以获取更多信息。” - 这意味着我的应用程序没有正确连接到数据库。

有人知道我的代码有什么问题吗?起初我认为这是一个范围问题,但是我在这里找不到我做错了什么。

提前感谢您的任何回复。

【问题讨论】:

    标签: php mysql database file include


    【解决方案1】:

    您不应该需要 global 关键字。包含直接在函数中定义这些变量。如果包含在函数之外,则需要全局关键字。

    【讨论】:

    • 现在已修复,谢谢! :) 我觉得自己没有弄清楚这一点有点傻!
    • 没问题。很高兴我能帮上忙。
    【解决方案2】:

    如果您已按原样包含设置文件,我不确定您是否需要 global 关键字。

    但是,通常最好的做法是尽可能避免使用全局变量。考虑将设置参数作为常量放入 Settings 类,因此您可以通过 Settings::host 等调用它们。

    全局变量,因为您引入了许多难以追踪的潜在错误,并且很可能是您的问题的原因。

    【讨论】:

      猜你喜欢
      • 2010-10-06
      • 2011-09-26
      • 2012-09-06
      • 1970-01-01
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 2011-01-13
      • 2010-10-05
      相关资源
      最近更新 更多