I am a bit confused about the purpose of the __toString() magic method in PHP. As I understand it, the methd should be called each time an object is converted to a string.
However, in practice, the invokation of this method seems very sporadic. Here is what I have found. I am using PHP 5.1.2 on Windows 2000 running through an Apache 2 server.
class Test
{
public function __toString()
{
return 'string cast';
}
}
$o = new Test;
echo($o); // __toString() invoked
echo($o . ' '); // __toString() not invoked
$s = ((string) $o);
echo($s); // __toString() not invoked
I would have expected the toString method to have been called in all the above cases. When I use SimpleXML however, which I can only assume, uses the toString method when objects are casted, the above behviour is as expect.
Is the simple xml using some secret method? And if so, what is it?