【问题标题】:Is it possible to use a class method as a callable parameter to array_map? [duplicate]是否可以使用类方法作为 array_map 的可调用参数? [复制]
【发布时间】:2018-08-18 13:10:31
【问题描述】:

我正在使用 php 5.6,我想做这样的事情:

class FooBar {
  public function foo() {
    echo "foo!";
    array_map($this->bar, [1,2,3]);
  }

  private function bar() {
    echo "bar!";
  }
}
(new FooBar)->foo();

这会产生以下错误:

注意:未定义的属性:FooBar::$bar

另外,是否可以将匿名函数声明为类属性?像这样的:

class FooBar {
  private $bar = function() {
    echo "bar!";
  }

  public function foo() {
    echo "foo!";
    array_map($this->bar, [1,2,3]);
  }
}
(new FooBar)->foo();

这给了我以下错误:

解析错误:语法错误,意外的“函数”(T_FUNCTION)

我能够得到我想要的结果:

class FooBar {
  function __construct() {
      $this->bar = function() {
        echo "bar!";
      };
  }

  private $bar;

  public function foo() {
    echo "foo!";
    array_map($this->bar, [1,2,3]);
  }
}
(new FooBar)->foo();

但这并不理想;我认为这些函数定义不属于构造函数 - 理想情况下,我希望它们是静态类方法。

【问题讨论】:

    标签: php anonymous-function


    【解决方案1】:

    你应该为你的函数指定上下文:

    class FooBar {
      public function foo() {
        echo "foo!";
        array_map([$this, 'bar'], [1,2,3]);
      }
    
      private function bar() {
        echo "bar!";
      }
    }
    (new FooBar)->foo();
    

    更多详情请查看http://php.net/manual/en/language.types.callable.php

    【讨论】:

      猜你喜欢
      • 2010-11-07
      • 2020-01-27
      • 1970-01-01
      • 2014-01-15
      • 2021-07-19
      • 2014-09-22
      • 2020-12-09
      • 2019-10-10
      • 1970-01-01
      相关资源
      最近更新 更多