__toString method is not so magic before PHP 5.2!

written by netinfluence 14 août 2009
__toString method is not so magic before PHP 5.2!

With Object Oriented Programmation, it is often useful to display an object quickly and easily.
The PHP langage has a magic object method to do that :

This method, if it is defined, will be automatically called (magic !) when the Object is displayed.
It’s nice, no ? But if your Php version is prior to 5.2, the magic method is not called !

Example :

In Php 5.2.1 :

But with Php before 5.2 :

So, to be sure of the behavior of your script, you can call directly the __toString() method.

You may also like

1 comment

Macmade 17 août 2009 at 14 h 22 min

This issue only affects string concatenation.
Prior to PHP 5.2, the __toString() method is called only when the object is printed directly.

So the following will work, even if that’s ugly… ; )

print ‘There is a ‘;
print $Car;
print ‘ and a ‘;
print $redCar;

Reply

Leave a Comment

*