在 分配变量 之前,
必须使用
global关键字。否则,您可以在函数内部声明一个局部变量,然后调用对尚不存在的global的引用。在其他功能中,使用了不存在的全局变量。
__
$connection``$connection``$connection
function dbconnect(){ // Global first to be sure the subsequent $connection is the global // rather than a new one local to this function global $connection; $sql = "localhost"; $username = "------"; $password = "-----"; // Now this modifies the global $connection $connection = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $connection); }更具可读性的是使用
$GLOBALS数组:
function dbconnect(){ $sql = "localhost"; $username = "------"; $password = "-----"; // Using the $GLOBALS superglobal array $GLOBALS['connection'] = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $GLOBALS['connection']); }最好的办法是
$connection从
dbconnect()其他函数中返回并使用该值:
function dbconnect(){ $sql = "localhost"; $username = "------"; $password = "-----"; $connection = mysql_connect($sql, $username, $password) or die("unwable to cct"); $databse = mysql_select_db("-------", $connection); // Return from the function return $connection; }// call as $connection = dbconnect();// and define your other functions to accept $connection as a parameter


