How to use $ this in a closure in php

I have a function like this:

class Service {
    function delete_user($username) {   
        ...
        $sessions = $this->config->sessions;
        $this->config->sessions = array_filter($sessions, function($session) use ($this){
            return $this->get_username($session->token) != $username;
        });
    }
}

      

but that doesn't work because you cannot use $this

internally use

, is it possible to execute a function that is a member of the Service class inside a callback? Or do I need to use foreach for loop?

+3


source to share


2 answers


$this

always available in (non-static) closures since PHP 5.4, don't need use

it.

class Service {
    function delete_user($username) {   
        ...
        $sessions = $this->config->sessions;
        $this->config->sessions = array_filter($sessions, function($session) {
            return $this->get_username($session->token) != $username;
        });
    }
}

      



See PHP Manual - Anonymous Functions - Automatic Linking $ this

+5


source


You can just apply it to something else:

$a = $this;
$this->config->sessions = array_filter($sessions, function($session) use ($a, $username){
   return $a->get_username($session->token) != $username;
});

      



You also need to convey $username

, otherwise it will always be true.

+1


source







All Articles