1
$f = function($v) {
    return $v + 1;
}

echo $f(4);
// output -> 5

The above works perfectly fine. However, I cannot reproduce this correctly when f is a property of a 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);

The above will result in an error:

Call to undefined method MyClass::f()
ma77c
  • 1,052
  • 14
  • 31

2 Answers2

5

I think the problem is that it is trying to make sense of

echo $this->f($a);

And as you've found it wants to call a member function f in the class. If you change it to

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

It interprets it as you want it to.

PHP 5.6 Thanks to ADyson for the comment, think this works

$f = $this->f;
echo $f($a);
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
2

While Nigel Ren's answer (https://stackoverflow.com/a/50117174/5947043) will work in PHP 7, this slightly expanded syntax will work in PHP 5 as well:

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);

See https://eval.in/997686 for a working demo.

ADyson
  • 57,178
  • 14
  • 51
  • 63