How to use $this in closure in php

断了今生、忘了曾经 提交于 2019-11-30 02:46:09

问题


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?


回答1:


$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




回答2:


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.



来源:https://stackoverflow.com/questions/44482168/how-to-use-this-in-closure-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!