2012-03-20 59 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等對它們進行調用。

全局變量,因爲您已經引入了很多可能很難追查的潛在錯誤,以及成爲你的問題的原因。