iptracker
answered May 19 '23 00:00
The __toString method in PHP is a magic method that allows an object to define how it should be converted to a string when it is treated as a string. It is automatically called when an object is used in a string context, such as when it is concatenated with a string or when it is passed to echo or print.
Here's an example to illustrate its usage:
class MyClass {
private $data;
public function __construct($data) {
$this->data = $data;
}
public function __toString() {
return $this->data;
}
}
$obj = new MyClass("Hello, world!");
echo $obj; // Output: Hello, world!
In this example, the MyClass object is defined with a private property called $data, and the __toString method is implemented to return the value of $data when the object is treated as a string. So when we echo the $obj variable, it automatically calls the __toString method to convert the object to a string and outputs its content.
Using __toString can be helpful when you want to control the string representation of an object or when you need to convert an object to a string for a specific purpose.