PHP invalid string concatenation with object instance, what error is thrown?

38 Views Asked by At

I noticed one of my script fails because of an invalid concatenation between a string and an object instance that doesn't implement __toString(). Here's a minimal reproduction:

class Foo { }
$bar = new Foo();
echo "Hello " . $bar . "\n";
echo "OK";

This fails on the third line. The strange thing is that I'm not able to catch or detect the error in any way, unlike any other error I encountered since now. It just fails. Here's what I tried that didn't work:

  • catch the error wrapping the code inside a try ... catch block, trying catching Exception, Error and Throwable;
  • registering a shutdown function with register_shutdown_function() and using error_get_last() inside it, the shutdown function doesn't get called at all;
  • calling error_reporting(E_ALL), the shutdown function still doesn't get called.

The only trace is in the output if I use ini_set('display_errors', 1), it ironically says:

Catchable fatal error: Object of class Foo could not be converted to string

But still, looks like there's no way to catch this programmatically.

Tested in PHP 7.0.22 and PHP 7.0.33.

0

There are 0 best solutions below