0

I wrote a tiny function called load, to include multiple file at once, instead of using multiple include statements. Things work fine, except when I echo a variable, I keep getting the Undefined variable error.

Here are the files. The file that runs everything is inc-main.php. That's where the Undefined variable error is thrown on line 9.

Any help on this can be solved? I don't get any file include errors which means the file are being included. The only problem is with the Variables.

load.php

<?php

$paths = array(
    'iNa'=>ROOT.'/test/inc-a.php',
    'iNb'=>ROOT.'/test/inc-b.php',
);

function load($files) {
    global $paths;
    $files = func_get_args();
    foreach($files as $file) {
        echo ($paths[$file]).'<br>';
        require_once($paths[$file]);
    }
}

?>

inc-a.php

<?php

$name = 'Donald';
$city = 'Duckberg';

?>

inc-b.php

<?php

$location = 'San Francisco';

?>

inc-main.php

<?php

define('ROOT',$_SERVER['DOCUMENT_ROOT']);

include(ROOT.'/test/load.php');

load('iNa','iNb');

echo 'Hello, my name is '.$name.', and I live in '.$city.'!'; /* Line 9 */

?>
Norman
  • 6,159
  • 23
  • 88
  • 141
  • 1
    As you are doing the `require` inside a function, you are putting all of the variables in the scope of that function. – Nigel Ren Feb 24 '21 at 08:50
  • Ok. So what needs to be done here to solve this. I cannot declare every variable as global since they differ in each file... – Norman Feb 24 '21 at 08:53
  • Just write multiple `require` statements, is there a reason why you don't want to? – Nigel Ren Feb 24 '21 at 08:55
  • There are many. That's the reason I turned to this approach. – Norman Feb 24 '21 at 08:57
  • Only way to solve this (without going down totally ridiculous paths that involve `eval` or worse), would probably be to eliminate the function then. Specify what files you want to load in a global variable, and then embed your `load.php` _after_ that, so that it has access to the variable, and can loop over it directly (without that loop being wrapped into a function.) – CBroe Feb 24 '21 at 09:03

0 Answers0