【问题标题】:Calling anonymous functions defined as object variables in php [duplicate]调用在php中定义为对象变量的匿名函数[重复]
【发布时间】:2011-08-02 02:26:08
【问题描述】:

我有类似的php代码:

class Foo {
  public $anonFunction;
  public function __construct() {
    $this->anonFunction = function() {
      echo "called";
    }
  }
}

$foo = new Foo();
//First method
$bar = $foo->anonFunction();
$bar();
//Second method
call_user_func($foo->anonFunction);
//Third method that doesn't work
$foo->anonFunction();

php中有没有办法可以使用第三种方法来调用定义为类属性的匿名函数?

谢谢

【问题讨论】:

    标签: php class anonymous-function


    【解决方案1】:

    不直接。 $foo->anonFunction(); 不起作用,因为 PHP 将尝试直接调用该对象上的方法。它不会检查是否存在存储可调用的名称的属性。你可以拦截方法调用。

    将此添加到类定义中

      public function __call($method, $args) {
         if(isset($this->$method) && is_callable($this->$method)) {
             return call_user_func_array(
                 $this->$method, 
                 $args
             );
         }
      }
    

    该技术也在

    中进行了说明

    【讨论】:

    • 谢谢,至少现在我知道这是不可能的,但可以通过解决方法。
    猜你喜欢
    • 2014-09-11
    • 2015-12-03
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    相关资源
    最近更新 更多