How to use $this in closure in php

后端 未结 2 569
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-04 03:03

I have function like this:

class Service {
    function delete_user($username) {   
        ...
        $sessions = $this->config->sessions;
        $t         


        
相关标签:
2条回答
  • 2021-01-04 03:21

    $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

    0 讨论(0)
  • 2021-01-04 03:34

    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.

    0 讨论(0)
提交回复
热议问题