是否可以使用 class 方法作为 array_map 的可调用参数?

Is it possible to use a class method as a callable parameter to array_map?

我正在使用 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();

这会产生以下错误:

Notice: Undefined property: FooBar::$bar

或者,是否可以将匿名函数声明为 class 属性?像这样:

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

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

这给了我以下错误:

Parse error: syntax error, unexpected 'function' (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();

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

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

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