How do I go about loading vars from an include() within a function()?
I'm trying to get some variables from a .php file. I call a function which has an included file in it that has the vars I want but it won't return any. Within the function I can view the variables values, but not outside the function.
//MODULE INCLUDE
function moduleInclude($mid) {
$query = "SELECT file,type FROM sh_module WHERE mid = '{$mid}'";
$exe = mysql_query($query);
$row = mysql_fetch_array($exe);
$folder = moduleFolder($row['type']);
$output = include("../includes/modules/".$folder."/".$row['file']);
re开发者_如何学Cturn $output;
}
//Load the vars
moduleInclude($mod_ship);
$ship_meth = $MODULE_title_client;
//THE ^^^^ MODULE_title_client never returns anything :(
include does not return the content of file include just put the code of that file at the place where the file is included.
And the variables declared in the files are available after the include statement. but as you are trying to access them outside the function the variable will not be accessible as they are now function scope.
You could update your code to include that file from outside the function.
function moduleInclude($mid) {
$query = "SELECT file,type FROM sh_module WHERE mid = '{$mid}'";
$exe = mysql_query($query);
$row = mysql_fetch_array($exe);
$folder = moduleFolder($row['type']);
return "../includes/modules/".$folder."/".$row['file'];
}
//Load the vars
$include_path=moduleInclude($mod_ship);
include $include_path;
$ship_meth = $MODULE_title_client;
I think you can use something like this:
//MODULE INCLUDE
function moduleInclude($mid) {
$query = "SELECT file,type FROM sh_module WHERE mid = '{$mid}'";
$exe = mysql_query($query);
$row = mysql_fetch_array($exe);
$folder = moduleFolder($row['type']);
include("../includes/modules/".$folder."/".$row['file']);
return get_defined_vars();
}
//Load the vars from include file into array
$module_vars=moduleInclude($mod_ship);
//Use the desired variable
$ship_meth = $module_vars['MODULE_title_client'];
if I understood you correctly. It is really ugly and I suggest you learn more about variable scopes to make this code better as including in a function is almost always the wrong way to go. I think we need to know what hapens inside your include file "../includes/modules/".$folder."/".$row['file'] to help you better.
Just return an object at the end of your include file:
$foo = 1;
$bar = 2;
return array('foo' => $foo, 'bar' => $bar)
Then, include will return the array returned in the module.
精彩评论