在 "anonymous" 对象中使用 $this

Using $this in "anonymous" object

我正在使用以下 class 来模拟 PHP 中的匿名对象:

class AnonymousObject
{
    protected $methods = array();

    public function __construct(array $options) {
        $this->methods = $options;
    }

    public function __call($name, $arguments) {
        $callable = null;
        if (array_key_exists($name, $this->methods))
            $callable = $this->methods[$name];
        elseif(isset($this->$name))
            $callable = $this->$name;

        if (!is_callable($callable))
            throw new BadMethodCallException("Method {$name} does not exist");

        return call_user_func_array($callable, $arguments);
    }
}

(https://gist.github.com/Mihailoff/3700483)

现在,只要声明的函数独立存在,一切正常,但每当我尝试像这样从另一个函数调用一个函数时...

$anonymous = new AnonymousObject(array(
    "foo" => function() { $this->bar(); }, 
    "bar" => function() { } 
));

那我当然会 Fatal error: Using $this when not in object context

有什么办法可以解决这个问题吗?

您可以使用表示匿名函数的 Closure 实例的 bind() 或 bindTo() method

<?php
class AnonymousObject
{
    protected $methods = array();

    public function __construct(array $options) {
        $this->methods = $options;
    }

    public function __call($name, $arguments) {
        $callable = null;
        if (array_key_exists($name, $this->methods))
            $callable = $this->methods[$name];
        elseif(isset($this->$name))
            $callable = $this->$name;

        if (!is_callable($callable))
            throw new BadMethodCallException("Method {$name} does not exists");

        $callable = $callable->bindTo($this);
        return call_user_func_array($callable, $arguments);
    }
}

$anonymous = new AnonymousObject(array(
    "foo" => function() { echo 'foo'; $this->bar(); }, 
    "bar" => function() { echo 'bar'; } 
));

$anonymous->foo();

(示例不太正确,因为它只适用于匿名函数;不适用于所有其他 callable() 替代方案,例如 $this->name 部分)

打印 foobar.