Carey
Carey

Reputation: 670

Undefined method when using anonymous functions

PHP returns Call to undefined method stdClass::fragmentr() for the following code:

$core = new \StdClass;

$core->fragmentr = function($frag) {
    $path = sprintf("fragments/%s.php", $frag);

    if(is_file($path)) {
        include $path;
    } else {
        header("Location: ./?p=500");
        exit;
    }
}

/* SNIP */

$core->fragmentr('header');

However, the function $core->fragmentr is clearly defined as an anonymous function assigned to a variable. Any ideas?

Upvotes: 1

Views: 830

Answers (1)

Rizier123
Rizier123

Reputation: 59681

This is because your stdClass doesn't have a method called: fragmentr, but it has a property called: fragmentr so you can do something like this:

$property = $core->fragmentr;
$property("header"); 

You can't call your Closure directly as you can see, so you have to assign it to a variable and then you can call it

Upvotes: 2

Related Questions