0

I can assign a function to a class variable in PHP, i.e. to $this->variable.

However, when I try to execute the function, it fails with:

FATAL ERROR Call to undefined method a::f()

Here is a snippet to illustrate the problem:

<?php

new a();

class a
{
    private $f;
    function __construct()
    {
        $g = function() { echo "hello g"; };
        $g(); //works

        $this->f = function() { echo "hello f"; };
        $this->f();  //FATAL ERROR Call to undefined method a::f()
    }
}
IanS
  • 1,459
  • 1
  • 18
  • 23

1 Answers1

0

It looks like the syntax is confusing PHP.

Assign the function back to a local variable and all is well!

<?php

new a();

class a
{
    private $f;
    function __construct()
    {
        $g = function() { echo "hello g"; };
        $g();

        $this->f = function() { echo "hello f"; };
        $f = $this->f;   //ASSIGN TO LOCAL VARIABLE!!!
        $f();
    }
}
IanS
  • 1,459
  • 1
  • 18
  • 23