在#34; anonymous"中使用$ this;宾语

时间:2015-07-12 12:25:09

标签: php anonymous-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

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:5)

您可以使用代表匿名函数的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-&gt; name部分)

打印foobar