Where and why do we use __toString() in PHP?

Stann picture Stann · Mar 2, 2011 · Viewed 27.2k times · Source

I understand how it works but why would we practically use this?

<?php
    class cat {
        public function __toString() {
            return "This is a cat\n";
        }
    }

    $toby = new cat;
    print $toby;
?>

Isn't this the same as this:

<?php
    class cat {
        public function random_method() {
            echo "This is a cat\n";
        }
    }

    $toby = new cat;
    $toby->random_method();
?>

can't we just use any other public method to output any text? Why do we need magic method like this one?

Answer

Lightness Races in Orbit picture Lightness Races in Orbit · Mar 2, 2011

You don't "need" it. But defining it allows your object to be implicitly converted to string, which is convenient.

Having member functions that echo directly is considered poor form because it gives too much control of the output to the class itself. You want to return strings from member functions, and let the caller decide what to do with them: whether to store them in a variable, or echo them out, or whatever. Using the magic function means you don't need the explicit function call to do this.