php - PHP5 - 将类属性作为函数调用时出错
问题描述
$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()
解决方案
我认为问题在于它试图理解
echo $this->f($a);
正如您发现的那样,它想要调用f
类中的成员函数。如果您将其更改为
echo ($this->f)($a);
它会按照您的意愿进行解释。
PHP 5.6 感谢 ADyson 的评论,认为这行得通
$f = $this->f;
echo $f($a);
推荐阅读
- javascript - keyup eventListener 和文本输入字段
- python - 如何将从 Google Drive 下载的数据保存在文件中 - Python Drive API
- r - 最大化唯一对,包括两个列表中的所有元素
- javascript - 是否有用于查找索引以拍摄基于 HTML5-JavaScript-Canvas 的视频播放器的快照的功能
- laravel - 如何为所有 Lumen 路由使用 auth:api 中间件?
- gradle - 收集父项目构建目录中的文件
- python-3.x - 比较文字字符串与 subprocess.Popen PowerShell 输出失败
- php - 使用 PHP 从查询字符串中获取倒数第二个参数
- android - 如何将 Shrinker (R8) 与 react-native 一起使用
- sql - 将列数据放入正确的目标列sql ssis