类实例上的PHP闭包


PHP Closure On Class Instance

如果我有一个类,比如:

class MyClass
{
   public function foo() 
   {
      echo "foo";
   }
}

然后在类外实例化它,并尝试在其中创建一个匿名函数:

$mine = new MyClass();
$mine->bar = function() {
   echo "bar";
}

然后试着把它称为$mine->bar(),我得到:

致命错误:调用中未定义的方法MyClass::bar()。。。

如何在类实例上创建匿名函数/闭包

旁白:在你告诉我应该重新思考我的逻辑或正确使用接口和OOP之前,在我的情况下,这是一种方便的方法,适用于一个废弃类的这个特定实例,试图清理遗留的过程应用程序。是的,我使用的是PHP 5.3+

请参阅我的博客文章:http://blog.flowl.info/2013/php-container-class-anonymous-function-lambda-support/

你需要添加一个神奇的__call功能:

public function __call($func, $args) {
    return call_user_func($this->$func, $args);
}

问题是在这个构造中,您可以从公共范围调用私有方法我建议而不是简单地向未定义的类添加新变量。您可以使用magic __set函数和捕获容器中所有未定义的变量(=数组,如我的博客文章中所述)来避免这种情况,并将call_user_func行为更改为仅在数组内部调用:

// inside class:
public $members = array();
public function __call($func, $args) {
    // note the difference of calling only inside members:
    return call_user_func($this->members[$func], $args);
}

__call

这会奏效的。

class Foo {
    public $bar;
    public function __construct()
    {
        $this->bar = function()
        {
            echo 'closure called';
        };
        $this->bar();
    }
    public function __call($method, $args) {
        return call_user_func($this->$method, $args);
    }
}
new Foo();

正在创建函数。PHP在调用它时遇到问题。

脏,但有效:

$f = $mine->bar;
$f();