Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP equivalent of JavaScript bind

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

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

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

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

like image 791
user3292788 Avatar asked Jun 19 '26 06:06

user3292788


2 Answers

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: 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: 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 ";
}

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

like image 91
georg Avatar answered Jun 21 '26 20:06

georg


Actually, $this does refer to $qux when called in that context.

You can't use $this in contexts other than an object method, so if you took something like this:

function test() {
    echo $this->baz;
}

It wouldn't work, no matter what you do.

like image 34
Madara's Ghost Avatar answered Jun 21 '26 18:06

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!