How to Use the PHP __toString() Magic Method

In this article, we show how to use the __toString() magic method in PHP.
The __toString method in PHP is one that allows us to call an object and see its components as a string.
So by using the echo and print function and having the object in the parameters of the echo or print function, the __toString() magic method is automatically called and it can allow us to see all the contents of an object (the properties of the object).
You'll see what I mean when you see the example code shown below.
But for now, realize, that the __toString() magic method is automatically called when we use the PHP echo or print function and place an object of a class inside of the echo or print function.
We then can use the __toString() method to output all of the contents of the object, such as all the object properties.
This saves us a lot of work of using getter methods to access the values of objects.
We simply can use the __toString method to output all of the properties of a n object. Not only that, but you can really do anything with the __toString method such as display sentences using object properties.
So as an example code, we create a class with private variable properties.
We then getter and setter methods to get and set values. We also include a __toString()
magic method so that we can output object properties.
So we create a class named cars.
We declare 2 private variables $type and $year. They are declared private, so that we can achieve encapsulation for the data.
We then create getter and setter methods to set and get our values.
We then create our __toString() magic method. The __toString() method must have a return value. So you must use the keyword return. After the return, you put the data that we want to return. Since the car object we are creating has a type and year, we output these values.
After this, we then create an object of the cars class, $car1.
We set the 2 values of the car, the type to a "Toyota Camry" and the year to 2013.
We then simply echo the object, $car1.
When we do this, what we put into the __toString method is output.
If we echoed out the object without the __toString method in the code,
the program would output a fatal error, such as the following:
Catchable fatal error: Object of class cars could not be converted to string.
Running the PHP code above yields the following output below.
Actual PHP Output
Car type: Toyota Camry
Car year: 2013
Related Resources
How to Create Getter and Setter Methods in PHP