PHP array_walk require_once

4

我想知道为什么不能将require_once用作array_walk的回调函数。我可以在匿名函数中包含它并运行它,但是如果直接使用会出现无效的回调错误:

$includes = array(
    'file1.php',
    'file2.php',
    'file3.php'
);
array_walk($includes, 'require_once');

3
require_once 不是一个函数,而是一种语言结构,因此它不能直接被作为回调函数调用。 - Mark Baker
1
如果您尝试使用array_walk($includes, 'echo'),由于echo是语言结构而不是函数,它也会出现无效回调的错误。 - Michael Berkowski
+1 给前面两条评论。但说真的,你为什么不在这里使用 foreach() 循环呢? - Spudley
谢谢大家,我刚刚像zigi说的那样做了一个foreach循环,但让我困扰的是我不能在一行上完成它并保持我的代码更加简洁。 - Peter
4个回答

6

require_once 不是 PHP 函数,而是一种控制结构。


3

你将会浪费更多时间来找出问题所在。只需要使用:

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

2

您可以创建

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

其他人说得对,这不是一个函数。它在你编写的PHP代码模式之外运行。即使在函数内部调用,文件的内容也会被带入全局命名空间中,如上所示。
例如,我使用它来执行以下操作:
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);
}

0
如Martin所写,require_once不是一个函数,所以你用array_walk的解决方案无法工作。如果你想要包含多个文件,你可以尝试使用以下代码:
function require_multi($files) 
{
    $files = func_get_args();
    foreach($files as $file)
    {
        require_once($file);
    }
}

使用方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接