PHP › Magic Methods
How does the __toString magic method let you control how an object is represented when it is used in a context expecting a string, such as being echoed directly?
IntermediateAnswer
The __toString magic method defines what string should be produced whenever an object is used in a context that expects a string, such as being directly echoed or concatenated with another string, letting you provide a natural, readable text representation of an object's data without requiring calling code to manually call a separate formatting method every time it needs to display that object as text.
class Money {
public function __construct(private float $amount, private string $currency) {}
public function __toString(): string {
return number_format($this->amount, 2) . ' ' . $this->currency;
}
}
echo new Money(29.99, 'USD');Real-world example A Money value object implements __toString so that simply echoing an instance directly produces a nicely formatted price string, letting the object be used naturally within templates without requiring a separate explicit formatting call every time.