在 PHP 中接受函数作为参数

2022-08-30 07:08:55

我一直在想是否可以在PHP中将函数作为参数传递;我想要一些类似的东西,当你用JS编程时:

object.exampleMethod(function(){
    // some stuff to execute
});

我想要的是用 exampleMethod 中的某个地方执行该函数。这在PHP中可能吗?


答案 1

如果您使用的是 PHP 5.3.0 或更高版本,则可以这样做。

请参阅手册中的匿名函数

在你的例子中,你可以这样定义:exampleMethod

function exampleMethod($anonFunc) {
    //execute anonymous function
    $anonFunc();
}

答案 2

只是为了添加到其他函数中,您可以传递一个函数名称:

function someFunc($a)
{
    echo $a;
}

function callFunc($name)
{
    $name('funky!');
}

callFunc('someFunc');

这将在 PHP4 中工作。


推荐