PHP5 - 将 class 属性 作为函数调用时出错
PHP5 - Error when calling class property as function
$f = function($v) {
return $v + 1;
}
echo $f(4);
// output -> 5
上面的工作非常好。但是,当 f
是 class 的 属性 时,我无法正确重现。
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()
我认为问题在于它试图理解
echo $this->f($a);
正如您所发现的,它想要调用 class 中的成员函数 f
。如果你把它改成
echo ($this->f)($a);
它会按照您的意愿进行解释。
PHP 5.6
感谢 ADyson 的评论,认为这有效
$f = $this->f;
echo $f($a);
虽然 Nigel Ren 的回答 () 将适用于 PHP 7,但这种稍微扩展的语法也适用于 PHP 5:
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
$func = $this->f;
echo $func($a);
}
}
$f = function($v) {
return $v + 1;
};
$myObject = new myClass($f);
$myObject->methodA(4);
有关工作演示,请参阅 https://eval.in/997686。
$f = function($v) {
return $v + 1;
}
echo $f(4);
// output -> 5
上面的工作非常好。但是,当 f
是 class 的 属性 时,我无法正确重现。
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()
我认为问题在于它试图理解
echo $this->f($a);
正如您所发现的,它想要调用 class 中的成员函数 f
。如果你把它改成
echo ($this->f)($a);
它会按照您的意愿进行解释。
PHP 5.6 感谢 ADyson 的评论,认为这有效
$f = $this->f;
echo $f($a);
虽然 Nigel Ren 的回答 (
class MyClass {
public $f;
public function __construct($f) {
$this->f = $f;
}
public function methodA($a) {
$func = $this->f;
echo $func($a);
}
}
$f = function($v) {
return $v + 1;
};
$myObject = new myClass($f);
$myObject->methodA(4);
有关工作演示,请参阅 https://eval.in/997686。