__toString() and exceptions
Posted: Sat Sep 05, 2009 1:20 pm
From PHP 5.2 and onwards it is no longer to throw Exceptions __toString() when using an object as a string (eg. in echo(), implode(), etc.).
The problem is that I have a SQL-builder which uses exceptions from __toString() if some data is missing (eg. a FROM part).
I use __toString() because it makes it a lot easier to concatenate strings with objects:
It is both faster and easier to read (and maintain), but the problem is that I still need to throw exceptions from them.
So what I've figured so far is that I probably need to embed the error in the generated string, and then search for the error string in the generated SQL before I send it to the database:
The problem is that I also need a delimiter for this error message, any suggestions?
And if you know any other way of throwing exceptions from code which is run in __toString(), please tell.
The problem is that I have a SQL-builder which uses exceptions from __toString() if some data is missing (eg. a FROM part).
I use __toString() because it makes it a lot easier to concatenate strings with objects:
Code: Select all
$string = implode(', ', $list);
$string = ‘’;
?foreach($list as $element)?
{?
if($element instanceof Some_class)?
{?
$string .= $element->getString();
? }?
else
? {
? $string .= $element;
? }?
}
// Instead of
$string = implode('', $list);So what I've figured so far is that I probably need to embed the error in the generated string, and then search for the error string in the generated SQL before I send it to the database:
Code: Select all
function getSQL()
{
$sql = $this->__toString();
self::detectError($sql);
// db interaction...
}And if you know any other way of throwing exceptions from code which is run in __toString(), please tell.