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 !")
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With