2012-02-25 40 views
9

是否有可能在PHP中使用匿名回调函数访问selfstatic$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)条款?

+1

从PHP 5.4开始,可以使用$ this。 – 2012-02-25 17:39:37

+0

*(相关)* [PHP 5.4 - '封$这种支持'(http://stackoverflow.com/questions/5734011/php-5-4-closure-this-support/5734109#5734109) – Gordon 2012-02-25 17:52:11

回答

13

随着PHP5.4这将是。目前这是不可能的。但是,如果你只需要访问公共属性,方法

$that = $this; 
function() use ($that) { echo $that->doSomething(); } 

对于常量没有理由使用合格的名称

function() { echo Classname::FOO; } 
+1

感谢回答。但是,如果我需要替换static :: FOO,也就是后期绑定,则不可能使用Classname。 – 2012-02-25 17:55:35

+1

听起来你比常数更多地寻找类属性(又名静态属性)。然而,在我的答案中的第一个例子,你应该能够像'$ that :: FOO'那样调用常量。 – KingCrunch 2012-02-25 18:09:32

+0

其实,我认为要做OP什么的,以后期绑定它不会是这样:$ that = static :: FOO; – 2013-08-27 13:50:11

4

只需使用标准方法:

Foo::BAZ; 

$baz = self::BAZ; 
... function($number) use($baz) { 
    $baz; 
} 
0

这个怎么样:

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