【发布时间】:2018-05-01 13:11:19
【问题描述】:
$f = function($v) {
return $v + 1;
}
echo $f(4);
// output -> 5
上面的工作非常好。但是,当f 是一个类的属性时,我无法正确重现这一点。
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
echo $this->f($a);
}
}
// When I try to call the property `f`, PHP gets confused
// and thinks I am trying to call a method of the class ...
$myObject = new myClass($f);
$myObject->methodA(4);
以上会报错:
Call to undefined method MyClass::f()
【问题讨论】:
-
第一个
$f等于什么? -
myClass($f);->$f是在哪里定义的? -
@AlivetoDie
f不是方法,它是存储在变量中的函数,作为类属性传递给构造函数