September 11th 2007 02:40 pm

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
?>

No Comments yet »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.

« Web Development With PLT Scheme | Being nice With Long Processes »