27

I have 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 this don't work because you can't use $this inside use, is it possible to execute function which is member of class Service inside a callback? Or do I need to use for or foreach loop?

jcubic
  • 61,973
  • 54
  • 229
  • 402

2 Answers2

59

$this is always available in (non-static) closures since PHP 5.4, no need to 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 binding of $this

Shira
  • 6,392
  • 2
  • 25
  • 27
0

You can just cast 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'll also need to pass $username through otherwise it'll always be true.

sjdaws
  • 3,466
  • 16
  • 20