如何在 php 的闭包中使用 $this

How to use $this in closure in php

我有这样的功能:

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;
        });
    }
}

但这不起作用,因为您不能在 use 中使用 $this,是否可以在回调中执行作为 class 服务成员的函数?或者我需要使用 for 或 foreach 循环吗?

您可以将其转换为其他内容:

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

您还需要通过 $username 否则它将始终为真。

$this 自 PHP 5.4 起在(非静态)闭包中始终可用,无需 use 它。

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;
        });
    }
}

PHP manual - Anonymous functions - Automatic binding of $this