PHP magic method YourClassName::__toString() has to return a string value There is nothing worse than a PHP Fatal Error :-) Your script terminates immediately and user sees 500 error page (or blank screen if you don't have one).
A nice fatal error i found recently has to do with __toString methods. Apparently there is a exact type check and __toString method in PHP has to return string. If you return something else it will cause exception to be thrown. Even if it would be casted otherwise like if( 1 == '1' ), in toString it has to be real string type.
Unfortunately for us we had some calls to other methods and one of them did not cast to string for integer values. There was no try catch block either so it boubbled up all the way to the top of the stack and caused script to die horribly : -)
Message you have to look out for is:
Catchable fatal error: Method Whatever::__toString() must return a string value
To try it out write script like PHP this:
class MySampleClass {
public function __toString() {
return 1;
}
}
try{
$foo = new MySampleClass();
echo " text ".$foo;
}catch(Exception $e){
echo "I did not expect anything to go wrong :- )";
}
Anything that uses MySampleClass in a string context would throw this exception as __toString is called.
Hope it helps someone.
Art
Main Blog Categories
About the author

Hi, my name is Artur Ejsmont,
welcome to my blog.
I am a passionate software engineer living in Sydney and working for Yahoo! Drop me a line or leave a comment.
Enjoy!
Comments
Also, don't pass any
Also, don't pass any parameters to __toString(), it is deprecated in newer PHP versions.
Post new comment