PHP array_walk require_once

I'm just wondering if anyone knew why I can't use require_onceas a callback for array_walk. I can just include it in an anonymous function and run it, but it gives an invalid callback error to use:

$includes = array(
    'file1.php',
    'file2.php',
    'file3.php'
);
array_walk($includes, 'require_once');
+4
source share
4 answers

require_once not a PHP function, but a management structure.

+6
source

You can create

function my_require_once ($name)
{
    require_once $name;
}

Other guys are right, this is not a function. It works outside the mode of the PHP code you are writing. The contents of the file are placed in the global namespace, even if it is called inside a function, as described above.

I use this, for example, to do something like

function my_log ($message, $extra_data = null)
{
    global $php_library;
    require_once "$php_library/log.php"; // big and complicated functions, so defer loading

    my_log_fancy_stuff ($message, $extra_data);
}
+2

, . :

$includes = array(
    'file1.php',
    'file2.php',
    'file3.php'
);
foreach($includes as $include) {
    require_once($include);
}
+2

As Martin wrote, not a function is required once, so your solution with array_walk does not work. If you want to include multiple files, you can try this:

function require_multi($files) 
{
    $files = func_get_args();
    foreach($files as $file)
    {
        require_once($file);
    }
}

Using:

require_multi("fil1.php", "file2.php", "file3.php");
0
source

All Articles