in PHP

PHP Magic Method __toString()

During OOP in PHP you need to debug the class, you can use the var_dump method but this isn't so user friendly, so you need an alternative to the var_dump(); PHP have released some magic method which can now be part of any class. One that is very useful for debugging in the __toString() method. This method will tell the class how to act if the object is treated as a string. For example if you go.

echo $obj;

You would normally get a fatal E_RECOVERABLE_ERROR level error, but if the class has a __toString() method PHP will call this method.

class obj{

     private $a = 1;
     private $b = 2;
     private $c = 3;

     public function __toString(){

          return $this->a . " " . $this->b . " " . $this->$c;



Now when you try to echo the object you will get a different results.

echo $obj;

//returns 1 2 3 To find out more about the magic methods in PHP go to website.

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email