【问题标题】:Pass content rather than variables to PHP function将内容而不是变量传递给 PHP 函数
【发布时间】:2020-05-07 15:24:52
【问题描述】:

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

这是一个 php 版本,说明如何在 javascript 中完成。

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
    }

});

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

【问题讨论】:

    标签: php function foreach


    【解决方案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

    【讨论】:

    • 我是个白痴。也需要在 JS 中这样做。忘了需要声明它是()里面的一个函数
    猜你喜欢
    • 2015-12-17
    • 2023-04-08
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    相关资源
    最近更新 更多