September 11th 2007
Auto Converting PHP Objects to Strings using the __toString() ‘Magic Method’
Ever wished there was a way to echo or print a PHP Object as if it were just a string and have it print something more usefull than Object id #1? In PHP5+ there is a Magic Method __toString() that will allow you to specify how you want your Object to react when converted to a string.
<?php
class Person{
private $firstName="Brien";
private $lastName="Wankel";
private $age="30";
...
public function __toString(){
return "{$this->firstName} {$this->lastName}";
}
}
$me = new Person();
echo("My name is {$me}"); // prints: My name is Brien Wankel
?>