2

According to Jason's suggestion about quick and dirty one-liner objects, I tried to create methods:

$obj = (object)array(
  "handler" => function() { return "Doom"; }
);

Calling it the intuitive way fails:

echo $obj->handler();
//Fatal error: Call to undefined method stdClass::handler()

But this way works:

$fnptr = $obj->handler;
echo $fnptr();
// "Doom"

Albeit calling it from associative array (not object) runs without fatal error:

$arr = array(
  "handler" => function() { return "Doom"; }
);
echo $arr["handler"]();
// "Doom"

Can you explain what's going on behind the scene? (I run on PHP 5.5.8)

Jan Turoň
  • 31,451
  • 23
  • 125
  • 169

1 Answers1

1

What PHP is trying to do here:

echo $obj->handler();

Is simply trying to call a normal method. But this method isn't defined, so you get:

Fatal error: Call to undefined method stdClass::handler()

But when you do:

$fnptr = $obj->handler;
echo $fnptr();

You assign the value of the property handler, which is an anonymous function, to the variable $fnptr. And then PHP doesn't try to call a method, it just calls your anonymous function and it works.

The same when you have an array element, which contains an anonymous function. PHP doesn't try to call a method, it just calls the anonymous function.


So there is no way you can get it to work like this:

echo $obj->handler();

For an object, since it always will try to call a method.

Rizier123
  • 58,877
  • 16
  • 101
  • 156