Home > Net >  PHP - Anonymous function inside an object
PHP - Anonymous function inside an object

Time:11-06

This will return error:

FATAL ERROR Uncaught Error: Call to undefined method stdClass::myfunc() in /var/www/html/index.php81(4) : eval()'d code:10 Stack trace: #0 /var/www/html/index.php81(4): eval() #1 {main} thrown on line number 10

How can I make this work?

<?php
$data = (object) [];

$data->foo = "whatever";

$data->myfunc = function () {
    echo "Yeah";
};

$data->myfunc(); // this makes error

call_user_func($data->myfunc); // this works as expected, strange

CodePudding user response:

You need to change your last line to this:

($data->myfunc)();

This is because the $data->myfunc() syntax refers to actual member functions on the object. So to first evaluate the property myfunc (this evaluates to a function) and then evaluate the function, you have to wrap it in parenthises or alternativly parse the property to a local variable before calling it as a function.

  •  Tags:  
  • php
  • Related