如何在PHP中使用$ this关闭 [英] How to use $this in closure in php
本文介绍了如何在PHP中使用$ 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;
});
}
}
但是这不起作用,因为您不能在use
内使用$this
,是否可以在回调内执行Service类的成员函数?还是我需要使用for或foreach循环?
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?
推荐答案
$this
始终在(非静态)闭包中可用,而无需use
.
$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;
});
}
}
这篇关于如何在PHP中使用$ this关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文