Why can't I pass variables into an included file in PHP?

情到浓时终转凉″ 提交于 2020-01-06 03:46:26

问题


I've had this problem before before with no real resolution. It's happening again so I'm hoping you experts can help.

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");

which calls this function:

function include_layout($template="") {
    include(SITE_ROOT.DS.'layouts'.DS.$template);
}

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?


回答1:


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.

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));



回答2:


Its because that variable is out of scope because you are including the file using a function. You either need to pass the variable to the function in another parameter or declare the variable as global within the function

either:

function include_layout($template="") {
    global $admin;
    include(SITE_ROOT.DS.'layouts'.DS.$template);
}

or:

function include_layout($template="",$admin="") {
    include(SITE_ROOT.DS.'layouts'.DS.$template);
}
include_layout("admin_header.php",$admin);



回答3:


It's a variable scoping issue. $admin is not defined inside the function, include_layout(). You can adjust your code a few ways. One is to say "global $admin;" inside include_layout(). Another is to set the variable, $admin, inside of "admin_header.php" if, for instance, the variable is only needed in that one layout context.




回答4:


It might matter because PHP doesn't give functions access to global variables unless you explicitly ask for it. Sanitizing your input would also be a good idea.



来源:https://stackoverflow.com/questions/1897243/why-cant-i-pass-variables-into-an-included-file-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!