gpt4 book ai didi

php - 将方法分配给变量/属性的语法

转载 作者:行者123 更新时间:2023-12-02 19:37:30 26 4
gpt4 key购买 nike

以下是非常简化的示例。我想知道 PHP 中是否可以,如果可以,正确的语法是什么。

class A{
private $func = null;

private default_func(){
return $this;
}

public function __construct(callable $user_func=null){
if($user_func){
$this->func = $user_func;
else{
$this->func = $this->default_func; ********* NOT WORKING ******
}

}

public function run(){
$this->func();*************** NOT WORKING IF USER DOES NOT GIVE def func
}
}

//NOT WORKING
$C = new A;
$C->run();

//WORKS
$D = new A(function(){echo 1;});
$D->run();

我在这里尝试让开发人员能够将函数发送到类中以在运行时覆盖默认行为。
我完全知道我可以简单地调用 else 中的默认函数,但如前所述,这是一个过于简化的示例。实际上有很多“默认”功能。

最佳答案

您可以使用call_user_func()来调用您需要的函数。这应该可以让您管理要调用的人。

  public function __construct(callable $user_func=null){
if($user_func){
$this->func = $user_func;
else{
$this->func = [$this, 'default_func'];
}

call_user_func($this->func);
}

关于php - 将方法分配给变量/属性的语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35161550/

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