You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP可调用闭包函数中访问变量?附类属性类型问题

问题1:在闭包中接收$friend变量

可以通过给闭包定义参数来接收call_user_func传递的$friend变量,原代码的问题在于闭包没有声明对应的参数,导致无法访问该变量。修改后的代码如下:

class Vacation 
{
  protected $onSuccess;
  protected $friend;

  public function onSuccess(callable $callback): self
  {
    $this->onSuccess = $callback;
    return $this;
  }

  public function go()
  {
    echo 'gone' . PHP_EOL;

    $this->friend = 'John';

    call_user_func($this->onSuccess, $this->friend);
  }
}

(new Vacation())
  ->onSuccess(function($friend){ // 声明参数$friend接收传递的值
    echo 'to the beach' . PHP_EOL;
    echo 'with ' . $friend . PHP_EOL; // 现在可正常访问
  })
  ->go();

执行后输出:

gone
to the beach
with John
问题2:$onSuccess属性的类型声明

有两种有效的类型声明方式,可根据需求选择:

  • callable类型:适用于需要接受所有可调用类型的场景(包括匿名函数、全局函数名、类方法的数组形式等)

    protected callable $onSuccess;
    
  • Closure类型:如果只需要接受匿名函数(闭包),可使用更精确的Closure类型声明

    protected Closure $onSuccess;
    

若选择Closure类型,需同步修改onSuccess方法的参数类型以保持一致性:

public function onSuccess(Closure $callback): self
{
  $this->onSuccess = $callback;
  return $this;
}

内容的提问来源于stack exchange,提问作者greener

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:32:41