How can I force the execution of a PHP file in a global scope?
I have a php file, say include.php which has the 开发者_如何学编程following contents:
<?php
$myVar = "foo";
?>
Now, I want to create a class, called GlobalInclude, which can include a file in the global scope:
class GlobalInclude {
public function include( $file="include.php" ) {
#do something smart
include $file
#do something smart
}
}
In it's current form, the $myVar variable will only be available inside the scope of the include function. I want to do something like:
GlobalInclude::include( "include.php" );
echo $myVar;
Output foo
Any ideas on how I can accomplish this?
Horribly ugly hack:
$GLOBALS[$myVar] = $myValue;
in the include.php (or whatever file you're actually using).
EDIT: Sorry, I misread your original post. You can do this by using get_defined_vars
to grab all variables in the current scope, and return them:
public function includeAndGetVars($file) {
include $file;
return get_defined_vars();
}
Then after you call your function, use extract
to dump the results into the current scope:
extract(includeAndGetVars("include.php"));
echo $myVar;
Thought I'd update the answer here.
I wrapped my app entry in a try catch, and threw a IncludeInGlobalException
with the file name as the message. Then, in the catch block, I included the file.
精彩评论