在单独的 PHP 脚本中访问全局变量


Accessing global variables in a separate PHP script?

我正在尝试从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);

但仍然不起作用。

我在"autoconf.php"文件中添加了一些echo语句,因此我知道它正在加载。

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

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

global $server_hostname;
$server_hostname = "localhost";

事实证明,该文件包含在应用程序的其他地方,因此当我调用require_once时,该文件根本没有被包含。我将其更改为仅require,现在它可以工作了。

也许文件未正确包含。

require_once 'includes/autoconf.php';   

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

试试这个

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

去看看。

使用常量怎么样?

定义("server_hostname","本地主机"(;定义("server_hostname","本地主机"(;

如果您包含文件并且变量是纯文本格式,而不是在函数/类中,则无需全局即可工作

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

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

<? //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!
?>

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

$server_hostname = "localhost";
global $server_hostname;
相关文章: