首页 > 解决方案 > 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()

标签: phpfunctionoopphp-5.6

解决方案


我认为问题在于它试图理解

echo $this->f($a);

正如您发现的那样,它想要调用f类中的成员函数。如果您将其更改为

echo ($this->f)($a);

它会按照您的意愿进行解释。

PHP 5.6 感谢 ADyson 的评论,认为这行得通

$f = $this->f;
echo $f($a);

推荐阅读