2012-02-25 5 views
9

È possibile accedere a classi/oggetti denominati come self, static e $this in callback anonimi in PHP? Proprio come questo:

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

C'è un modo per rendere comportarsi come con le variabili al solito, utilizzando use(self) clausola?

+1

Da PHP 5.4 è possibile utilizzare $ this. –

+0

* (correlato) * [PHP 5.4 - 'chiusura $ questo supporto'] (http://stackoverflow.com/questions/5734011/php-5-4-closure-this-support/5734109#5734109) – Gordon

risposta

13

Con PHP5.4 sarà. Per ora non è possibile. Tuttavia, se è necessario solo l'accesso alle proprietà pubbliche, metodo

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

per le costanti non v'è alcun motivo per non utilizzare il nome qualificato

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

Grazie per il risposta. Tuttavia, non è possibile usare Classname se ho bisogno di sostituire static :: FOO, cioè l'associazione tardiva. –

+1

Sembra che si stiano cercando proprietà di classe (cioè proprietà statiche), rispetto alle costanti. Tuttavia, con il primo esempio nella mia risposta dovresti essere in grado di chiamare la costante come '$ that :: FOO'. – KingCrunch

+0

In realtà, penso di fare quello che l'OP vuole con l'associazione tardiva non sarebbe: $ that = static :: FOO; –

4

Basta usare il modo standard:

Foo::BAZ; 

o

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

Che dire di questo:

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