对象方法的匿名函数 [英] Anonymous function for a method of an object

查看:21
本文介绍了对象方法的匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
直接调用分配给对象属性的闭包

为什么这在 PHP 中是不可能的?我希望能够为特定对象即时创建一个函数.

Why this is not possible in PHP? I want to be able to create a function on the fly for a particular object.

$a = 'a';
$tokenMapper->tokenJoinHistories = function($a) {
   echo $a;
};
$tokenMapper->tokenJoinHistories($a);

推荐答案

使用 $obj->foo() 你可以调用方法,但是你想调用一个属性 asem> 一个函数/方法.这只是混淆了解析器,因为他没有找到名为 foo() 的方法,但他不能期望任何属性是可调用的.

With $obj->foo() you call methods, but you want to call a property as a function/method. This just confuses the parser, because he didn't find a method with the name foo(), but he cannot expect any property to be something callable.

call_user_func($tokenMapper->tokenJoinHistories, $a);

或者你扩展你的映射器

class Bar {
  public function __call ($name, $args) {
    if (isset($this->$name) && is_callable($this->$name)) {
      return call_user_func_array($this->$name, $args);
    } else {
      throw new Exception("Undefined method '$name'");
    } 
  }
}

(这个快速编写的示例中可能存在一些问题)

(There are probably some issues within this quickly written example)

这篇关于对象方法的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆