【问题标题】:How to use $this in closure in php如何在 php 的闭包中使用 $this
【发布时间】:2017-11-12 21:51:05
【问题描述】:

我有这样的功能:

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 循环?

【问题讨论】:

    标签: php closures this anonymous-function


    【解决方案1】:

    $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

    【讨论】:

      【解决方案2】:

      你可以把它转换成别的东西:

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

      您还需要通过 $username 否则它总是正确的。

      【讨论】:

      • 分配不转换
      猜你喜欢
      • 2017-01-04
      • 2012-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多