2

I created a object inline with PHP to work as a model for my SQL table, and when I try to set a function to a object value, I get this error. I simplified the code to show the error:

PHP

$test = (object) [
    'autoValue'=>function($name) {
        return $name.' in table.';
    }
];

echo $test->autoValue('Rick');

I keep recieving the error:

Fatal error: Uncaught Error: Call to undefined method stdClass::autoValue() in

I need to run a function that is stored in autoValue in the object, and I cannot set the object with a class.

How can I do this?

1 Answers1

4

You should create a group around $test->autoValue using ( ):

echo ($test->autoValue)('Rick'); // Rick in table.

Full example :

$test = (object) [
    'autoValue'=>function($name) {
        return $name.' in table.';
    }
];
echo ($test->autoValue)('Rick'); // Rick in table.

Or using a variable

$callback = $test->autoValue;
echo $callback('Rick'); // Rick in table.
Syscall
  • 19,327
  • 10
  • 37
  • 52