If I have three files “index.php” “file.php” and “fns.php“
First example (it works):
index.php :
<?php
$var = "Variable Data";
include "file.php";
?>
file.php:
<?php
var_dump($var); #Output will be : string(13) "Variable Data"
?>
Second Example (it don’t work) :
index.php :
<?php
include "fns.php";
$var = "Variable Data";
load("file.php");
?>
fns.php :
<?php
function load($file) { include $file; }
?>
file.php
<?php
var_dump($var); #Output will be : NULL
?>
How to include files using functions like load() and keep variables working without additional Global $var; ?
My Solution :
<?php
function load($file)
{
$argc = func_num_args();
if($argc>1) for($i=1;$i<$argc;$i++) global ${func_get_arg($i)};
include $file;
}
#Call :
load("file.php", "var");
?>
Because you include the file inside of the function, the included file’s scope is that function’s scope.
In order to include additional variables, inject them into the function.
This way,
$varwill be available.You could even make things more dynamic:
And use it like this:
PHP will extract the variables into correct symbol names (
$var,$otherVar).