PHP等同于JavaScript绑定

问题描述:

首先请问我的英语不是母语,抱歉,如果它看起来粗糙,这是我第一次在此网站上发布. 我的问题很简单.假设我们有:

First excuse my english I'm not a native speaker and sorry if it looks rough, this is the first time that I post on this site. My problem is quite simple I think. Let's say, we have :

class A {

    function foo() {

        function bar ($arg){
            echo $this->baz, $arg;
        }

        bar("world !");

    }

    protected $baz = "Hello ";

}

$qux = new A;

$qux->foo();

在此示例中,"$ this"显然没有引用我的对象"$ qux".

In this example, "$this" obviously doesn't refer to my object "$qux".

我应该如何使它与"$ qux"相对应?

How should I do to make it reffer to "$qux"?

可能在JavaScript中:bar.bind(this, "world !")

As might be in JavaScript : bar.bind(this, "world !")

PHP没有嵌套函数,因此在您的示例中bar本质上是全局的.您可以使用闭包(=匿名函数)来实现所需的功能,闭包支持绑定自PHP 5.4起:

PHP doesn't have nested functions, so in your example bar is essentially global. You can achieve what you want by using closures (=anonymous functions), which support binding as of PHP 5.4:

class A {
    function foo() {
        $bar = function($arg) {
            echo $this->baz, $arg;
        };
        $bar->bindTo($this);
        $bar("world !");
    }
    protected $baz = "Hello ";
}

$qux = new A;
$qux->foo();

UPD:但是,bindTo($this)并没有多大意义,因为闭包会自动从上下文中继承this(同样在5.4中).因此,您的示例可以很简单:

UPD: however, bindTo($this) doesn't make much sense, because closures automatically inherit this from the context (again, in 5.4). So your example can be simply:

    function foo() {
        $bar = function($arg) {
            echo $this->baz, $arg;
        };
        $bar("world !");
    }

UPD2:对于php 5.3-这似乎只有通过这样的丑陋骇客才有可能实现:

UPD2: for php 5.3- this seems to be only possible with an ugly hack like this:

class A {
    function foo() {
        $me = (object) get_object_vars($this);
        $bar = function($arg) use($me) {
            echo $me->baz, $arg;
        };
        $bar("world !");
    }
    protected $baz = "Hello ";
}

此处get_object_vars()用于发布"受保护/私有属性,以使其在闭包中可访问.

Here get_object_vars() is used to "publish" protected/private properties to make them accessible within the closure.