在 PHP pre 5.4.0中的匿名函数中使用‘ $this’

PHP 手册指出

在 PHP 之前,不可能从匿名函数使用 $this 5.4.0

匿名函数页上。但是我发现我可以通过将 $this赋值给一个变量并在函数定义处将该变量传递给一个 use语句来使其工作。

$CI = $this;
$callback = function () use ($CI) {
$CI->public_method();
};

这是个好习惯吗?
使用 PHP 5.3访问匿名函数内部的 $this有更好的方法吗?

55769 次浏览

That seems alright if your passing by reference it's the correct way to do it. If your using PHP 5 you don't need the & symbol before $this as it will always pass by reference regardless.

This is fine. I should think you could do this also:

$CI = $this;

... since assignations involving objects will always copy references, not whole objects.

That is the normal way it was done.
b.t.w, try to remove the & it should work without this, as objects pass by ref any way.

It will fail when you try to call a protected or private method on it, because using it that way counts as calling from the outside. There is no way to work around this in 5.3 as far as I know, but come PHP 5.4, it will work as expected, out of the box:

class Hello {


private $message = "Hello world\n";


public function createClosure() {
return function() {
echo $this->message;
};
}


}
$hello = new Hello();
$helloPrinter = $hello->createClosure();
$helloPrinter(); // outputs "Hello world"

Even more, you will be able to change what $this points to at runtime, for anonymus functions (closure rebinding):

class Hello {


private $message = "Hello world\n";


public function createClosure() {
return function() {
echo $this->message;
};
}


}


class Bye {


private $message = "Bye world\n";


}


$hello = new Hello();
$helloPrinter = $hello->createClosure();


$bye = new Bye();
$byePrinter = $helloPrinter->bindTo($bye, $bye);
$byePrinter(); // outputs "Bye world"

Effectively, anonymus functions will have a bindTo() method, where the first parameter can be used to specify what $this points to, and the second parameter controls what should the visibility level be. If you omit the second parameter, the visibility will be like calling from the "outside", eg. only public properties can be accessed. Also make note of the way bindTo works, it does not modify the original function, it returns a new one.

Don't always rely on PHP to pass objects by reference, when you are assigning a reference itself, the behavior is not the same as in most OO languages where the original pointer is modified.

your example:

$CI = $this;
$callback = function () use ($CI) {
$CI->public_method();
};

should be:

$CI = $this;
$callback = function () use (&$CI) {
$CI->public_method();
};

NOTE THE REFERENCE "&" and $CI should be assigned after final calls on it has been done, again else you might have unpredictable output, in PHP accessing a reference is not always the same as accessing the original class - if that makes sense.

http://php.net/manual/en/language.references.pass.php