6

我正在尝试从 PHP 脚本中导入一些变量。这看起来很简单,但我无法让它工作。

该脚本包含一些像这样的全局变量:

$server_hostname = "localhost";
$server_database = "kimai";
$server_username = "root";
$server_password = "";
$server_conn     = "mysql";
$server_type     = "";
$server_prefix   = "kimai_";
$language        = "en";
$password_salt   = "7c0wFhYHHnK5hJsNI9Coo";

然后在我的脚本中,我想访问这些变量,所以我完成了:

require_once 'includes/autoconf.php';   
var_dump($server_hostname);

但这只是输出NULL。我也试过:

require_once 'includes/autoconf.php';

global $server_hostname;    
var_dump($server_hostname);

但仍然无法正常工作。

echo在“autoconf.php”文件中添加了一些语句,所以我知道它正在被加载。

知道如何访问这些变量吗?

4

7 回答 7

3

您必须首先将变量定义为全局变量:

global $server_hostname;
$server_hostname = "localhost";
于 2012-05-18T06:54:46.717 回答
2

事实证明,该文件已包含在应用程序的其他位置,因此当我调用 时require_once,该文件根本没有包含在内。我把它改成了just require,现在它可以工作了。

于 2012-05-19T03:29:12.610 回答
1

也许该文件未正确包含。

require_once 'includes/autoconf.php';   

检查您包含的当前工作目录autoconf.php

试试这个

if (file_exists('includes/autoconf.php')) require_once 'includes/autoconf.php';
else echo 'File not exists';

检查出来。

于 2012-05-18T06:56:55.077 回答
0

使用常量怎么样?

定义(“服务器主机名”,“本地主机”);定义(“服务器主机名”,“本地主机”);

于 2012-05-18T06:57:55.043 回答
0

如果包含文件并且变量是纯文本,而不是在函数/类中,则它可以在没有全局的情况下工作

转到您的 php.ini 并将 display_errors=On 和错误放入 E_ALL,这样您就会看到哪个是正确的原因

于 2012-05-18T07:08:09.300 回答
0

这是邪恶的,但它可能会完成工作。

<? //PHP 5.4+
\call_user_func(static function(){
    $globals = \get_defined_vars();
    include 'includes/autoconf.php';
    $newVars = \array_diff_key($globals, \get_defined_vars());
    foreach($newVars as $name => $value){
        \define($name, $value);
    }
});
//Variables defined in file are now constants!
?>
于 2012-05-18T07:54:51.357 回答
0

使用和更正全局变量的更好方法是首先为变量赋值,然后声明全局变量。这是:

$server_hostname = "localhost";
global $server_hostname;
于 2020-11-11T16:28:56.673 回答