php - 在php中调用定义为对象变量的匿名函数

标签 php class anonymous-function

<分区>

我有这样的 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 中有没有一种方法可以使用第三种方法来调用定义为类属性的匿名函数?

谢谢

最佳答案

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

将其添加到类定义中

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

此技术也在

中进行了解释

关于php - 在php中调用定义为对象变量的匿名函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5605404/

相关文章:

javascript - 为什么要自执行匿名函数

javascript - 在Javascript中调用匿名函数中的函数时如何使用 "this"关键字?

php - 类对象在 ob_start 回调中不起作用

php - PDO 创建临时表并选择

php - Virtual Box 中的访问被拒绝

c++ - 俄罗斯方 block :类的布局

java - 当类名已知时,动态检索给定类的Object类的java对象

php - 限制用户角色仅更改 Woocommerce 中的某些订单状态

java - 在 Droid 菜单中重复应用

javascript - 匿名函数名称在浏览器之间的行为不同?