2012-03-20 57 views
1

我目前正在重写我的旧PHP脚本,以便代码结构良好,以便将来更新。文件包含可能的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; 
    } 

} 

我以前的代码曾经完美地工作,但是现在我已经将变量转换为不同的文件,即我的应用程序不断输出“无法选择父母的晚餐桌。 “ - 这意味着我的应用程序没有正确连接到数据库。

有没有人有任何想法我的代码有什么问题?我认为这是一个范围问题,但我只是无法找出什么我做错了这里。提前

感谢您的任何答复。

回答

2

你不应该需要全局关键字。该包括直接定义函数中的变量,如果包括在功能之外,您需要全局关键字。

+0

现在修复它,谢谢! :)我觉得有点傻,因为我没有想到自己! – 2012-03-20 23:41:53

+0

没问题。很高兴我能帮上忙。 – dqhendricks 2012-03-20 23:52:09

1

我不确定你需要全局关键字,如果你已经包含你的设置文件。

但是,通常最好避免使用全局变量。考虑将设置参数设置为Settings类作为常量,因此您可以通过Settings :: host等对它们进行调用。

全局变量,因为您已经引入了很多可能很难追查的潜在错误,以及成为你的问题的原因。