将内容而不是变量传递给PHP函数

时间:2020-05-07 15:24:52

标签: php function foreach

是否可以将不是变量的内容传递给PHP函数,例如循环或类似的构造,以在其他函数中执行。

这是如何在javascript中完成的php版本。

function myFunction($content){

    // something important that needs to be done before content

    $content

    // something important that needs to be done after content

}

myFunction({

    foreach($things_we_have as $key => $val){
        // Things to do in centre of the function
    }

});

显然这不起作用。能做到吗?如果可以,怎么办?

1 个答案:

答案 0 :(得分:1)

您可以将Closures / anonymous functions用作函数的参数。

示例:

function myFunction($closure)
{

    // something important that needs to be done before content

    $closure($thingsWeHave);

    // something important that needs to be done after content

}

myFunction(function($thingsWeHave)
{
    foreach($thingsWeHave as $key => $val){
        // Things to do in center of the function
    }
});

其他示例是herehere