简体   繁体   English

如何将全局变量传递给函数中的包含文件

[英]How to pass global variables to an included file in a function

function test_something() {
    global $test;
    echo '<div>';
    include("random_file.php");
    echo '</div>
}

random_file uses $test, but even when I define $test as global I get the undefined variable $test error when I run test_something random_file使用$ test,但是即使我将$ test定义为global,我在运行test_something时也会得到未定义的变量$ test错误

My actual example has about 20 variables in the file I am including and the file is 500 lines long. 我的实际示例在我包含的文件中大约有20个变量,文件长500行。

you should be fine accessing it via global $test; 您应该可以通过global $test;很好地访问它global $test; or $GLOBALS['test'] inside random_file.php - there is no parametrisation of includes to my knowledge $GLOBALS['test'] random_file.php $GLOBALS['test'] -据我所知,没有包含参数化

EDIT: you should even be able to use $test as-is in your include since its already locally bound and includes inherit the scope 编辑:您甚至应该甚至可以在包含中使用$test ,因为它已经本地绑定并包含继承范围

您不必将变量传递到任何包含的文件,当您在主文件中声明变量时,便可以包含其他文件...您可以在任何需要的地方使用它:包含文件意味着将代码复制到主文件。

The answer is to define $test a global within the included file as well. 答案是在包含的文件中也定义$ test全局变量。

Then the undefined error goes away and $test can be used. 然后未定义的错误消失,可以使用$ test。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM