0

I have a closure that is a global variable and I would like to run it in a class I made. However, when I try the following code, I get the error, Exception: Call to undefined method TestClass::globalFunction().

Here is what I'm trying:

$globalFunction = function($var){
    echo "works $var";
};

class TestClass{
    private $globalFunction;
    function __construct(){
        $this->globalFunction = $GLOBALS['globalFunction'];
    }
    function testFunc(){
        $this->globalFunction('a');
    }
}
$arr = new TestClass();
$arr->testFunc();
JVE999
  • 3,327
  • 10
  • 54
  • 89

1 Answers1

0

Because $this->globalfunction is a variable, not a method, you need to wrap it in parentheses to force PHP to evaluate $this->globalfunction before attempting to call it as a function i.e.

function testFunc(){
    ($this->globalFunction)('a');
}

Output:

works a

Demo on 3v4l.org

Nick
  • 138,499
  • 22
  • 57
  • 95