为什么我不能将变量传递到PHP中的包含文件? [英] Why can't I pass variables into an included file in PHP?
问题描述
我之前之前没有真正的问题解析度。它正在再次发生,所以我希望你的专家可以提供帮助。
I've had this problem before before with no real resolution. It's happening again so I'm hoping you experts can help.
我根据$ _GET数组在index.php上设置了一个变量。所以我使用这段代码:
I set a variable on my index.php based on the $_GET array. So I use this code:
$admin = isset($_GET['admin']) ? $_GET['admin'] : "dashboard";
在此之下,我使用一个函数来包含我的布局:
Below that, I use a function to include my layout:
include_layout("admin_header.php");
调用此函数:
function include_layout($template="") {
include(SITE_ROOT.DS.'layouts'.DS.$template);
}
到目前为止,这么好,一切正常。但是,如果我尝试从admin_header.php文件中回显$ admin变量,我什么也得不到。就好像它没有设置一样。我甚至在我包含头文件之前使用 echo $ admin;
测试它,并在那里输出,但它不是从admin_header.php文件的角度设置的。
So far, so good, everything works. But if I try to echo the $admin variable from within the admin_header.php file, I get nothing. It's as if it's not set. I even test it by using echo $admin;
right before I include the header file, and it outputs there, but it's not set from the admin_header.php file's perspective.
为什么会发生这种情况?是否与使用函数包含而不是直接包含它有关?如果是这样,那为什么会这么重要?
Why would this happen? Is it something to do with using a function to include, rather than including it directly? And if so, WHY would that matter?
推荐答案
除非您明确说明,否则无法访问全局变量。您必须在函数中放入 global $ admin
才能访问该变量。
It's not possible to access global variables unless you say so explicitly. You have to put global $admin
in the function to be able to access the variable.
原因是你在函数中包含了文件,所以$ admin变量存在于全局范围内,而包含的文件存在于函数范围内。
The reason is you include the file inside of a function, so the $admin variable lives in the global scope, while the included file lives in the functions scope.
function include_layout($template="") {
global $admin;
include(SITE_ROOT.DS.'layouts'.DS.$template);
}
另一种可能性是使用提取方法。
Another possibility is to use the extract method.
function include_layout($template="", $variables) {
extract($variables, EXTR_SKIP);
include(SITE_ROOT.DS.'layouts'.DS.$template);
}
include_layout("test.php", array('admin' => $admin));
这篇关于为什么我不能将变量传递到PHP中的包含文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!