PHP To String Magic Method

Posted on

What does it do?

The to string magic method is used to specify how you would like the object to react when used as a string.

Why would you use it?

If you want to log or print out information on the class in a quick and easy way or avoid errors incase the object is used as a string.

class User {

    protected $name;
    protected $age;
    protected $location;

    public function __construct($name, $age, $location)
    {
        $this->name = $name;
        $this->age = $nage;
        $this->location = $location;
    }

    public function __toString()
    {
        return 'User Information: name: ' . $this->name . ', Age: ' . $this->age . ' Location: ' . $this->location;
    }
}

$user = new User('John', 26, 'Leeds, Uk');

echo $user; // echoes User Information: name: John, Age: 26 Location: Leeds, UK;

This function is particularly useful if you need to log something about the object for whatever reason, instead of writing a method why not just use the baked in PHP functionality?

Or how about when you are using the builder design pattern. If you have an object that is built up overtime to output a final something.

For example;

You would like to build up a collection of assets and output their entirety when completed. The class below allows you to add assets systematically and when finished echo the class out to output all the assets.

class Assets{

    protected $queue = array();

    public function add($script){
        $this->queue[] = $script;
    }

    public function __toString(){    
        $output = '';    
        foreach($this->queue as $script){
            $output .= '<script src="'.$script.'"></script>';
        }    
        return $output;
    }
}

$assets = new Assets();

$assets->add('link-to-vue.js');

if (true) {
    $assets->add('cdn-link.js');
}

echo $assets; // <script src=“link-to-vue.js”></script><script src=“cdn-link.js”></script>

Sidenote

toString() always has to return a string, if not you get a fatal error.

When echoing out properties to avoid a possibly “undefined property” my advice would be to wrap the to string output in a try/catch. This way if the property does not exist this way you will get “ returned, or you could always return an error as a string

public function __toString()
{
    try
        return (string) $this->name;
    }
    catch (Exception $exception)
    {
        return '';
    }
}