PHP将方法绑定到另一个类 [英] PHP binding method to another class

查看:142
本文介绍了PHP将方法绑定到另一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以将Foo类的方法绑定到Bar类吗?为什么下面的代码引发警告无法将方法Foo :: say()绑定到Bar类的对象"?用函数代替方法代码可以正常工作.

Can i bind method of class Foo to class Bar? And why the code below throws a warning "Cannot bind method Foo::say() to object of class Bar"? With function instead of method code works fine.

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

P.S. I know about extending) it is not practical question, just want to know is it real to bind non-static method to another class

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();

下面的代码可以正常工作

Code below works fine

 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();

推荐答案

当前不支持此功能.如果要将闭包绑定到新对象,则它不能是假闭包,否则新对象必须与旧对象兼容(

This is currently not supported. If you want to bind a closure to a new object, it must not be a fake closure, or the new object must be compatible with the old one (source).

所以,什么是假闭包:假闭包是从Closure::fromCallable创建的闭包.

So, what is a fake closure: A fake closure is a closure created from Closure::fromCallable.

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

This means, you have two options to fix your problem:

  1. Bar必须与Foo的类型兼容-因此只需使BarFoo扩展.

  1. Bar must be compatible with the type of Foo - so just make Bar extend from Foo, if possible.

使用非绑定函数,例如匿名函数,静态函数或类外部函数.

Use unbound functions, like annonymous, static or functions outside of classes.

这篇关于PHP将方法绑定到另一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆