Last Updated: May 31, 2021
·
1.983K
· filipekiss

Magic Method to make an object "Echoable"

PHP Magic Methods are great. The construct probably it the most famous magic method of all. But today, I'm here to talk to you about `toString()`;

__toString is a nice little method to be executed when you're trying to convert your object to an string.

A simple use for this method is to return a var_dump of the current object:

<?php

Class SomeClass{

  function __toString(){
      ob_start();
      var_dump($this);
      return ob_get_clean();
  }
}

$myClass = new SomeClass;

echo $myClass; //It's the same as calling 'var_dump( $myClass )';

This is just a really simple example of how this method behaves. Let's say you have a class you use to manage you users... You can use the __toString method to make echo $user returns the user name, so you don't need to call $user->username or something like that. In my opinion, __toString is meant to make it easiear when you need to access a common property or anything like that. Just remember: it MUST be an string. You can't return, let's say, an array. It will return an E_RECOVERABLE_ERROR to remind you that will need it as a String.

I guess that's it. Hoped it helped you at least a little.

Happy coding :)