1

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.

lorenzo-s
  • 16,603
  • 15
  • 54
  • 86
  • 1
    The function in https://www.php.net/manual/en/class.errorexception.php#errorexception.examples may help if you want to process it. – Nigel Ren Feb 21 '20 at 08:20
  • i wonder what could be a real world application for concatenating a newly instantiated object to a string, i haven't tried to do that in anyway possible before, could someone enlighten me with this too – Kevin Feb 21 '20 at 08:20
  • @Kevin, I think they were just showing it as an example as to how to reproduce the problem. In reality in could happen after a large amount of processing. – Nigel Ren Feb 21 '20 at 08:22
  • @NigelRen Many thanks, the duplicate and the manual link look exactly what I was searching for. I focused on the string concatenation instead of the non-catchable catchable error, that's why I couldn't find it myself. – lorenzo-s Feb 21 '20 at 08:24
  • 1
    Oddly enough it is actually catchable in PHP 7.4 which tells me it might have something to do with the changes to make `__toString` able to throw exceptions – apokryfos Feb 21 '20 at 08:25
  • @Kevin I just noticed a cron script failing abruptly, without any clue in my logs. I couldn't get the reason until I debugged it step by step, and found that simple error where I mistakenly try to concatenate a variable that is not a string. That wasn't intentional. – lorenzo-s Feb 21 '20 at 08:28
  • @apokryfos Interesting, thanks. – lorenzo-s Feb 21 '20 at 08:28
  • @lorenzo-s gotcha thanks for the context, i haven't done any real world application using that way so im curious and apparently, it was done inadvertently – Kevin Feb 21 '20 at 08:34

0 Answers0