【问题标题】:PHP binding method to another classPHP 将方法绑定到另一个类
【发布时间】:2018-04-20 07:50:51
【问题描述】:

我可以将 Foo 类的方法绑定到 Bar 类吗?为什么下面的代码会抛出警告“无法将方法 Foo::say() 绑定到类 Bar 的对象”?使用函数而不是方法代码可以正常工作。

附:我知道扩展)这不是实际问题,只是想知道将非静态方法绑定到另一个类是否真实

class Foo {

    public $text = 'Hello World!';

    public function say() {
        echo $this->text;
    }

}

class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable(array(new Foo, 'say'));
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();

下面的代码可以正常工作

 function say(){
    echo $this->text;
 }
 class Bar {

    public $text = 'Bye World!';

    public function __call($name, $arguments) {
        $test = Closure::fromCallable('say');
        $res = Closure::bind($test, $this);
        return $res();
    }

}

$bar = new Bar();
$bar->say();

【问题讨论】:

  • 你可以扩展到那个类
  • 不确定,但可以尝试将say() 更改为静态?
  • 我知道)但是这个关于闭包和绑定的问题
  • 我重新审视了你的问题,但我不明白你在问什么。你是什​​么意思:“只想知道将非静态方法绑定到另一个类是真的吗”
  • 对我来说很明显..在 JS 中经常使用它

标签: php php-7


【解决方案1】:

目前不支持此功能。如果你想将一个闭包绑定到一个新对象上,它一定不能是假闭包,或者新对象必须与旧对象兼容(source)。

那么,什么是假闭包假闭包是从Closure::fromCallable创建的闭包。

这意味着,您有两种方法可以解决您的问题:

  1. Bar 必须与 Foo 的类型兼容 - 所以只需使 Bar 如果可能,从Foo 扩展。

  2. 使用未绑定的函数,例如匿名函数、静态函数或类之外的函数。

【讨论】:

  • 澄清“当前”部分:永远不会支持。我们在 PHP 7.1 中明确禁止这样做。以前,可以执行这种重新绑定(当然,使用 ReflectionMethod::getClosure() 而不是 Closure::fromCallable(),它只在 PHP 7.1 中添加),但现在不再允许这样做。
猜你喜欢
  • 1970-01-01
  • 2021-09-17
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-12-24
  • 1970-01-01
  • 1970-01-01
  • 2012-03-06
相关资源
最近更新 更多