You can use eval() to get your require_once to run in a global context. This method would require changing just two lines in your main program file: your function call, and the return value from the function. No changes to foo.php would be required, or other global iteration tricks.
function includeFooFile() {
# don't do the require in the fn, let the caller do it
return 'require_once("foo.php");';
}
$foo = 23;
eval(includeFooFile());
echo($foo."\n"); # will print 42.
There are a couple of catches to the eval() approach though:
Do not include any user-supplied or untrusted strings in the returned & eval'd code: see the eval() documentation as to why. This shouldn't be an issue for require_once's because in general you will be including only known source files.
Your includeFooFile function cannot use for itself any of the variables or functions declared in foo.php, because they do not exist until after the return. If you wanted includeFooFile to manipulate foo.php's changes further, you'd need to define a follow-up function and call that after the eval, or change the return value to include the follow-up code after the require_once. However, the latter approach may get tricky with nested quoting, so a heredoc is recommended. Double-quote style heredocs, shown below allow you to use variables, perhaps parameters passed to includeFooFile. Single-quote heredocs, like <<<'EOINCLUDE', would make quoting much easier if you know for sure you do not require variable interpolation.
function includeFooFile() {
return
<<<EOINCLUDE
require_once('foo.php');
\$foo++;
EOINCLUDE;
}
Prints 43.
If you wanted super simple, you could do away with the eval and simply return the name of the file to require_once, and then have the caller just require that:
function includeFooFile() {
return 'foo.php';
}
$foo=23;
require_once(includeFooFile());
echo($foo."\n"); # will print 42.
But then you cannot add any follow-up code, nor require_once two or more files within includeFooFile. However, you do eliminate the always-uncomfortable eval().
Note: if you were to have to further nest the call to includeFooFile itself inside another function, you would have to create a bubbling-up chain of these evals somehow. What I've demonstrated would not be adequate as is.
Ideally, PHP devs will eventually give us an optional parameter to require_once to specify we want it done in a global scope.
require_once
is explicitly set where you define the use of it. – Heidarequire_once()
in a function? – Medullatedrequire_once
will be of limited use as it will define the variables only once? – Heida