【问题标题】:php array_filter anonymous function passing $this [duplicate]php array_filter匿名函数传递$this [重复]
【发布时间】:2013-11-03 15:59:11
【问题描述】:

如果想这样做:

    $filteredValues = array_filter($rawValues, function($rawValue) {
        return $this->validateValue($rawValue);
    });

validateValue 是同一类中的私有方法。

我怎样才能以这种方式在 array_filter 中使用 $this 上下文?

【问题讨论】:

    标签: php


    【解决方案1】:

    如果你使用 PHP 5.3,PHP 不识别 $this 为闭包,你需要做一个类似 JavaScript 的技巧:

    $self = $this;
    $filteredValues = array_filter($rawValues, function($rawValue) use ($self) {
        return $self->validateValue($rawValue);
    });
    

    请注意,以上内容只会让您通过对象的公共 API 访问该对象。这与 5.4 对 Closure 重新绑定的支持不同,后者允许完全访问 $this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 2014-09-11
      • 2014-03-05
      • 2019-11-23
      • 2011-05-11
      • 2011-01-29
      • 1970-01-01
      相关资源
      最近更新 更多