gpt4 book ai didi

php - 类中的匿名函数

转载 作者:行者123 更新时间:2023-12-04 22:09:17 25 4
gpt4 key购买 nike

有没有更好的方法在类中调用匿名函数?这是一个简单的例子,可以清楚地说明我的意思。

class foo
{
private $call_back_1 = null;
private $call_back_2 = null;

function __construct($func1, $func2)
{
$this->call_back_1 = func1;
$this->call_back_2 = func2;
}


function provokeCallBacks()
{
//this does not work, and gives an error
$this->call_back_1();


//I would like to avoid this
$method = $this->call_back_2;
$method();
}
}

$call1 = function(){ echo "inside call 1"};
$call2 = function(){ echo "inside call 2"};

$test = new foo(call1, call2);

$test->provokeCallBacks();

* 更新 1:请忽略任何语法错误,因为我是为演示目的而即时编写的。 *

在 foo:provokeCallBacks 中,我试图调用匿名函数,但是第一种方法不起作用并给出错误。第二个有效,但我必须使用一个名为“$method”的临时变量来进行调用,这有点愚蠢。

我想知道是否有更好的调用匿名函数的方法。

最佳答案

call_user_func($this->call_back_1);

关于php - 类中的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12602753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com