Is there anyway to for an included file to be used in a parent scope to the one it was called in? The following example is simplified, but does the same job.
In esse
function include_use_scope($file, $defined_variables)
{
extract($defined_variables);
include($file);
}
include_use_scope("file.php", get_defined_vars());
get_defined_vars()
gets ALL variables defined in the scope it is called in. extract()
takes an array and defines them as local variables.
extract(array("test"=>"hello"));
echo $test; // hello
$vars = get_defined_vars();
echo $vars['test']; //hello
Thus, the desired result is achieved. You might want to strip out the superglobals and stuff from the variables however, as overwriting them might be bad.
Check out this comment for stripping the bad ones out.
In order to get the reverse, you could do something like this:
function include_use_scope($file, $defined_variables)
{
extract($defined_variables);
return include($file);
}
extract(include_use_scope("file.php", get_defined_vars()));
include.php
// do stuff
return get_defined_vars();
But all in all, I don't think you are going to get the desired effect, as this was not how PHP was built.
The only way I know how to is to use the superglobal array.
main.php:
$GLOBALS['myVar'] = 'something bar foo';
$success = myPlugin('included.php');
if($success)
{
echo $GLOBALS['myResult'];
}
included.php:
<?php
$GLOBALS['myResult'] = strlen($GLOBALS['myVar']);