php - 在 "anonymous"对象中使用 $this

标签 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

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

最佳答案

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

<?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

关于php - 在 "anonymous"对象中使用 $this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31367735/

相关文章:

php - 使用 GROUP BY 获取最新条目

php - 防止多人编辑同一个表单

php - 如何使用 GTFS-realtime 获取日程提醒和延误?

php - 如何检测匿名类的实例?

java - 匿名类中的 Activity 名称是什么

Scala 单元到匿名类

javascript - JQuery - 在表单中填充数据的正确方法

php - Yii 2 : virtual fields in ActiveRecords

java - java中的装饰器设计模式

java - 这是匿名内部类的变体吗?