This seems kind of limitation to me, indeed, if you use __toString() magic method for anything other than simple object variables concatenation, your code should be able to throw exceptions. Consider you have an object that generates XML as output, and you decide to provide even nicer interface, so that anyone using it in string context to get access to that XML. XML generation might not go well, and the obvious way to let the client know about this is to throw an exception. However, this is not possible (most probably due to some internal architecture limitations – as I honestly see no reason why this ideologically wrong).
One (not quite pretty) way to still provide some feedback from __toString() is using trigger_error:
public function __toString()
{
try {
$output = $this->generateXml();
return $output;
} catch(Exception $e) {
trigger_error($e->getMessage(), E_USER_ERROR);
return '';
}
}
If you know of a better option, let me know!
Return $e;
Exception’s toString is very useful.
And don’t put XML generation in toString!
Well, I don’t put XML generation into __toString(), I have separate method for that. __toString() just _proxies_ the XML-generating method, just to give a nice alternative of calling getXml() directly.
If you wanna generate XML create method toXml().
Well, you don’t seem to understand my point. I already have toXml() method, and I am not urging you to create XML in __toString(), moreover it’s not about XML at all. It is all about possible complex logic in __toString() that might require exception support.
You see if in order to overcome the deficiency of __toString, we would introduce the new methods, well, then I have great news for you – we don’t need __toString’s magic, long before we had toString() methods when we wanted to output our object’s string representation.
Hi Victor,
I totally understand what you mean as this behavior annoys me. I set out trying to find a solution for this but I ran out of time and have to move on to something else. What I got so far is that Exceptions and Errors are handled differently in PHP. Maybe we can catch the error generated by __toString with one of those PHP functions:
set_error_handler
set_exception_handler
I’ll keep you updated when I resume researching this issue.
On a separate note, please install the «Subscribe To Comments» WordPress plugin. It will allow your visitors, if they want, to receive notifications when someone posts a new comment.
Cheers