文件include可能存在PHP作用域问题


Possible PHP scope issue with file include?

我目前正在重新编写一个旧的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;
    }
}

我的旧代码过去工作得很好,但现在我已经将变量更改为不同的文件,我的应用程序不断输出"无法选择家长餐桌。请联系管理员了解更多信息。"-这意味着我的应用软件没有正确连接到数据库。

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

提前感谢您的回复。

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

如果你已经按原样包含了设置文件,我不确定你是否需要全局关键字。

然而,通常最好尽量避免全局变量。考虑将设置参数作为常量放入settings类中,这样您就可以通过settings::host等调用它们。

全局变量引入了许多潜在的错误,这些错误很难追踪,很可能是导致问题的原因。