Took me longer than I expected to figure this out, and thought others might find it useful.
I created a function (safeinclude), which I use to include files; it does processing before the file is actually included (determine full path, check it exists, etc).
Problem: Because the include was occurring inside the function, all of the variables inside the included file were inheriting the variable scope of the function; since the included files may or may not require global variables that are declared else where, it creates a problem.
Most places (including here) seem to address this issue by something such as:
<?php
global $myVar;
$nowglobal = $GLOBALS['myVar'];
?>
But, to make this work in this situation (where a standard PHP file is included within a function, being called from another PHP script; where it is important to have access to whatever global variables there may be)... it is not practical to employ the above method for EVERY variable in every PHP file being included by 'safeinclude', nor is it practical to staticly name every possible variable in the "global $this" approach. (namely because the code is modulized, and 'safeinclude' is meant to be generic)
My solution: Thus, to make all my global variables available to the files included with my safeinclude function, I had to add the following code to my safeinclude function (before variables are used or file is included)
<?php
foreach ($GLOBALS as $key => $val) { global $$key; }
?>
Thus, complete code looks something like the following (very basic model):
<?php
function safeinclude($filename)
{
foreach ($GLOBALS as $key => $val) { global $$key; }
if ($exists==true) { include("$file"); }
return $exists;
}
?>
In the above, 'exists' & 'file' are determined in the pre-processing. File is the full server path to the file, and exists is set to true if the file exists. This basic model can be expanded of course. In my own, I added additional optional parameters so that I can call safeinclude to see if a file exists without actually including it (to take advantage of my path/etc preprocessing, verses just calling the file exists function).
Pretty simple approach that I could not find anywhere online; only other approach I could find was using PHP's eval().