在PHP中的类属性中存储闭包函数

Mp *_*ega 2 php methods closures class function

好的,我确实有下面的代码

<?php
    class foo{
       public $bar = NULL;

       public function boo(){
          $this->bar();
       }
    }

    $mee = new foo();

    //save a closure function on the property
    $mee->bar = function(){
        echo 'hahaha';
    };

    //invoke the closure function by using a class method
    $mee->boo();
?>
Run Code Online (Sandbox Code Playgroud)

你可以看到它在这里运行http://codepad.org/s1jhi7cv

现在我想要的是将闭包函数存储在类方法中.

井盖是可能的,因为我在这里阅读有关它的文档http://php.net/manual/en/functions.anonymous.php

这可能吗?我做错了吗?请纠正我

Dav*_*dom 11

您在codepad.org上的示例代码不起作用,因为codepad.org使用PHP 5.2.5,并且仅在5.3中添加了闭包支持.

但是,您的代码也不能在支持闭包的PHP版本中工作,尽管您会收到不同的错误:http://codepad.viper-7.com/Ob0bH5

这是目前PHP的限制.$obj->member()查找名为的方法member,不会查看属性以查看它们是否可调用.坦率地说,这很烦人.

我知道的唯一方法是在没有call_user_func()/的情况下完成这项工作call_user_func_array():

public function boo() {
   $func = $this->bar;
   $func();
}
Run Code Online (Sandbox Code Playgroud)

  • @Mahan它无法在codepad.org上运行(参见上面的编辑),至少需要5.3.作品[这里](http://codepad.viper-7.com/dB3ckH) (2认同)