有没有办法将对象上下文传递给匿名函数而不用传递$this
作为参数?
class Foo {
function bar() {
$this->baz = 2;
# Fatal error: Using $this when not in object context
$echo_baz = function() { echo $this->baz; };
$echo_baz();
}
}
$f = new Foo();
$f->bar();
答案 0 :(得分:11)
您可以将$this
分配给某个变量,然后在定义函数时使用use
关键字将此变量传递给函数,但我不确定它是否更易于使用。无论如何,这是一个例子:
class Foo {
function bar() {
$this->baz = 2;
$obj = $this;
$echo_baz = function() use($obj) { echo $obj->baz; };
$echo_baz();
}
}
$f = new Foo();
$f->bar();
值得注意的是,$obj
将被视为标准对象(而不是$this
),因此您将无法访问私有和受保护的成员。