【发布时间】:2012-03-20 09:59:43
【问题描述】:
在我的小项目中一切正常,直到我决定稍微清理一下并将与数据库相关的 php 文件移动到他们自己的文件夹中。然后事情变得奇怪了。
我在这里尝试使用两个函数:
function getEntries () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error);
echo $dbHost; // prints host
return $result;
}
function getBiggestMonth () {
require_once("mysqliVariables.php");
$mysqli = new mysqli($dbHost, $dbUname, $dbPwd, $dbName);
echo $dbHost; // prints nothing! why?
$sql = "statement...";
$result = $mysqli->query($sql) or die($mysqli->error); // this line does not run, of course.
return $result;
}
我使用不同文件(和文件夹)中的另一个函数来调用这些函数,如下所示:
function listTasks() {
require_once("db/mysqliFunctions.php");
// Get entries using mysqli.
$tasks = getEntries();
echo "<pre>";
var_dump($tasks);
echo "</pre>"; // program works fine this far.
$bm = getBiggestMonth(); // program breaks somehow during this function call.
我的变量在 php 文件中,如下所示:
<?php
$dbHost = "host";
$dbUname = "username";
$dbPwd = "password";
$dbName = "databasename";
?>
如果我切换函数的调用顺序,那么 getBiggestMonth() 运行良好,而另一个则不会。此外,当所有文件都位于同一个文件夹中时,所有这些工作都很好(这些函数是类中的静态函数,但这不应该成为问题,同样的问题在这里仍然存在) ,所以我不明白这里的变量范围如何不同,并且 require_once 应该处理其他事情。帮忙?
【问题讨论】:
标签: php scope mysqli require-once