【问题标题】:PHP: access class method in callback function defined outside of classPHP:在类外定义的回调函数中访问类方法
【发布时间】:2018-01-24 06:18:52
【问题描述】:

我有一门课

class Foo
{
  public function runWithCallback($custom_callback) {
    ...
    return call_user_func_array($custom_callback, [$arg_a, $arg_b]);
  }
  public function aHelperMethod($arg_a) {
    ...
  }
}

当我使用类时

$foo = new Foo();
$foo->runWithCallback(function($arg_a, $arg_b) {
  ...
  // now I need to use helper method "aHelperMethod"
  $this->aHelperMethod($arg_c); // wrong code
  ...
});

当然,上面的代码不起作用,因为$this 在那个匿名函数中毫无意义。

有可能做我想做的事吗?谢谢。

【问题讨论】:

  • 你可以访问这样的功能$foo->aHelperMethod()
  • @BilalAhmed 谢谢,但我发现它有点“脏”。有没有更清洁的方法?

标签: php class callback


【解决方案1】:

好的,感谢@BilalAhmed 的评论,我发现了一种“肮脏”的做法:

$foo = new Foo();
$foo->runWithCallback(function($arg_a, $arg_b) use ($foo) {
  ...
  // now I need to use helper method "aHelperMethod"
  $foo->aHelperMethod($arg_c); // wrong code
  ...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    • 2020-06-02
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多