__toString method is not so magic before PHP 5.2!

Share:
Comments: 1
Related articles

This article was originally created by Emilien Vuillaume (Left our team)

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 :

class Object{    public function __toString()    {    }}

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 :

class Car{    public $color;

    public function __construct($color = 'white')    {       $this->color = $color;    }

    public function __toString()    {        return $this->color . ' car';    }}

$Car    = new Car();$redCar = new Car('red');

echo "There is a " . $Car . " and a " . $redCar;

In Php 5.2.1 :

There is a white car and a red car

But with Php before 5.2 :

There is a Object #1 and a Object #2

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

Leave a Reply

One Response to “__toString method is not so magic before PHP 5.2!”

  1. Macmade says:

    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;