是否可以访问PHP中匿名回调中引用为self
、static
和$this
的类/对象?就像这样:
class Foo {
const BAZ = 5;
public static function bar() {
echo self::BAZ; // it works OK
array_filter(array(1,3,5), function($number) /* use(self) */ {
return $number !== self::BAZ; // I cannot access self from here
});
}
}
使用use(self)
子句,有什么方法可以让它像对待普通变量一样工作吗?
有了PHP5.4,这是可能的。目前还不可能。但是,如果您只需要访问公共属性,方法
$that = $this;
function () use ($that) { echo $that->doSomething(); }
对于常量,没有理由不使用限定名称
function () { echo Classname::FOO; }
只需使用标准方式:
Foo::BAZ;
或
$baz = self::BAZ;
... function($number) use($baz) {
$baz;
}
这个怎么样:
class Foo {
const BAZ = 5;
$self = __class__;
public static function bar() {
echo self::BAZ; // it works OK
array_filter(array(1,3,5), function($number) use($self) {
return $number !== $self::BAZ; // access to self, just your const must be public
});
}
}