Just as you can define a toString() method in programming languages such as Java and C#, you can have __toString() magic methods for PHP classes too.
The advantage of using __toString() in PHP is that you can use object variables with echo or print directly. Also, you can avoid the PHP error ‘Catchable fatal error: Object of class xyz could not be converted to string in filename.php on line x’ when accidentally passing an object variable to an echo or print statement.
Take a look at this example:
class Car { var $brand; var $modelName; var $modelYear; public function __toString() { return $this->brand.' '.$this->modelName.' '.$this->modelYear; } }
The Car class has a __toString() method that returns a string representing the object. The Car class can be used as follows:
$car1 = new Car(); $car1->brand = 'Toyota'; $car1->modelName = 'Camry'; $car1->modelYear = '2010'; echo $car1;
This example returns the output: “Toyota Camry 2010″
In the absence of the __toString() method, PHP would have returned the error “Catchable fatal error: Object of class Car could not be converted to string in example1.php on line 17″.
No comments yet.