在A.php
中,我包含config.php
和B.php
:
include_once("path/to/config.php");
include_once("path/to/B.php");
B.php
是其他脚本使用的通用脚本。我不知道包含 B.php
的脚本是否也包含 config.php
所以在 B.php
中有
include_once("path/to/config.php");
问题是在A.php
中我可以从config.php
读取所有变量,但在B.php
中它们不是没有设置。如果我在 B.php
中执行 print_r(get_included_files())
,我可以看到 config.php
已包含在内。
这是什么原因造成的?我怎样才能正确地包含 config.php
以便它将在 B.php
中可用(以及 A.php
包含的其他脚本.. .)?
编辑:添加脚本内容。
config.php
:
<?php
$db_ip = "";
$db_login="";
$db_pass ="";
$db_port = 30050;
$db_name_hlstats = "";
$db_name_csgo = "";
$db_name_report = "";
$db_web_host = "";
$db_web_port = "3306";
$db_web_login = "";
$db_web_pass = "";
$db_web_name = "";
B.php
:
<?php
function GetServers()
{
include_once("/data/web/virtuals/93680/virtual/config/config.php");
include_once("/data/web/virtuals/93680/virtual/scripts/getPDO.php");
include_once("/data/web/virtuals/93680/virtual/scripts/PDOQuery.php");
print_r(get_included_files()); // shows config.php in included files
echo "servers.php | $db_ip:$db_port"; // variables show nothing
$pdo = getPDOConnection($db_ip, $db_login, $db_pass, $db_name_csgo, $db_port);
$query = "SELECT ...";
$result = getPDOQueryResult($pdo, $query, __FILE__, __LINE__);
$res = array();
foreach ($result as $row)
{
$res[$row["server_id"]] = $row;
}
return $res;
}
最佳答案
您没有在 B.php
中获得结果的原因是您正在使用 include_once
,它只会包含尚未包含的文件。在您的情况下,您将其包含在 A.php
中,这样它就会发现它已经被加载,并且不会在 B.php
中再次加载它(又名它将跳过包含)。
如果您在 B.php
函数中使用 include
而不是,您应该会看到结果。
require_once
和 include_once
通常最适合包含包含类/方法/函数的库,这样您就不会意外地尝试多次定义它们。
示例
class MyClass{
// Contains some methods
}
当包含执行此操作的文件时:
include 'MyClass.php';
include 'MyClass.php';
当它尝试加载第二个包含时,您将收到一条错误消息“MyClass”已被定义。
执行此操作时:
include_once 'MyClass.php';
include_once 'MyClass.php';
PHP 将跳过加载第二个包含文件,并且您不会收到表明该类已定义的错误。
因此,对于您 B.php
来说,执行 require_once
或 include_once
是个好主意,这样您就不必重新定义函数并得到一个错误。
您还应该注意 include*
和 require*
之间存在差异。
使用 include*
时,如果无法加载文件,脚本将继续运行,并且根据您正在执行的操作可能会损坏数据/结果。
使用 require*
时,如果无法加载文件,脚本将结束执行。
关于php - 如何正确包含配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33398544/