How to use $this in closure in php

后端 未结 2 570
爱一瞬间的悲伤
爱一瞬间的悲伤 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

提交回复
热议问题