I need to test an object to see if it can be cast as a string. If it can't, it normally throws a 'catchable fatal error':

$dom = new DomDocument( '1.0', 'utf-8' );
$stringified = (string)$dom;
/* Throws:
Catchable fatal error:  Object of class DOMDocument could not be converted to string
*/

Since it's 'catchable', I tried to trap it in a try..catch block, but this doesnt work because it is indeed an error, rather than an exception:

// if we can't cast it, just make it an empty string
try { $stringified = (string)$dom; } catch(Exception $e) { $stringified = ''; }

So I assume the only way to 'catch' it would be to set up a custom global error handler, but not only does that blow in terms of program structure, there's always the possibility that one of the classes in their __toString method might also be setting a global error handler, which would introduce all kinds of subtle bugs:

set_error_handler();
$stringified = (string)$dom;
restore_error_handler();

Is there any conceivable way to test this without setting a global error handler?

    Write a Reply...