简体   繁体   English

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

[英]How to use $this in closure in php

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?但这不起作用,因为您不能在use使用$this ,是否可以在回调中执行作为 Service 类成员的函数? Or do I need to use for or foreach loop?还是我需要使用 for 或 foreach 循环?

$this is always available in (non-static) closures since PHP 5.4, no need to use it. $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;
        });
    }
}

See PHP manual - Anonymous functions - Automatic binding of $this参见PHP 手册 - 匿名函数 - $this 的自动绑定

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.您还需要传递$username否则它将始终为真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM