4

I was just wondering if anyone knew why I can't use require_once as a callback for array_walk. I can just include it in an anonymous function and run that, but it gives an invalid callback error for the usage:

$includes = array(
    'file1.php',
    'file2.php',
    'file3.php'
);
array_walk($includes, 'require_once');
4
  • 3
    require_once isn't a function, it's a language construct, so it can't be called directly as a callback function Commented Jan 7, 2014 at 16:50
  • 1
    ...it would also error with an invalid callback if you tried to use array_walk($includes, 'echo') as echo is a language construct not a function. Commented Jan 7, 2014 at 16:51
  • +1 to both previous comments. But seriously, any good reason why you aren't just using a foreach() loop here? Commented Jan 7, 2014 at 16:53
  • Thanks guys, just did a foreach loop like zigi said, but it perturbed me that I couldn't do it on a single line and keep my code extra clean. Commented Jan 7, 2014 at 18:23

4 Answers 4

6

require_once is not a PHP function, but a control structure.

Sign up to request clarification or add additional context in comments.

Comments

3

You are going to waste more time finding out what's wrong. Just use:

$includes = [
    'file1.php',
    'file2.php',
    'file3.php'
];
foreach($includes as $include) {
    require_once($include);
}

Comments

2

You could create

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

The other guys are right, it's not a function. It operates outside the mode of the PHP code you write. The contents of the file are brought into the global namespace, even if it is called within a functiion, as above.

I use this, for example to do stuff 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);
}

Comments

0

As Martin wrote, require once is not a function, so your solution with array_walk is not been working. If you want to include multiple files, you can try to use this:

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

Usage:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.