Le funzioni anonime non utilizzano lo scope lessicale, ma $this
is a special case and will automatically be available inside the function as of 5.4.0. Il tuo codice dovrebbe funzionare come previsto, ma non sarà portabile a versioni precedenti di PHP.
Di seguito vi non lavoro:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) {
echo $methodScopeVariable;
});
}
Invece, se si vuole iniettare le variabili in campo di applicazione della chiusura, è possibile utilizzare la parola chiave use
. Il seguente sarà lavoro:
protected function _pre() {
$methodScopeVariable = 'whatever';
$this->require = new Access_Factory(function($url) use ($methodScopeVariable) {
echo $methodScopeVariable;
});
}
In 5.3.x, è possibile ottenere l'accesso al $this
con la seguente soluzione:
protected function _pre() {
$controller = $this;
$this->require = new Access_Factory(function($url) use ($controller) {
$controller->redirect($url);
});
}
Vedere this question and its answers per maggiori dettagli.
fonte
2013-05-03 17:30:12
Ah, buono a sapersi è diverso in PHP5.4 (che ancora non ha ancora raggiunto i miei pacchetti di Debian Stable ... potrebbe essere necessario installarlo manualmente). – Wrikken
Ho bisogno di un "use ($ this)" o 5.4 ti dà automaticamente accesso a $ this? – Charles
5.4.0+ associa automaticamente '$ this'. Guarda [questo breve video] (http://youtu.be/-Ph7X6Y6n6g) spiegandolo. –