How can objects be converted to strings for output in PHP?
To convert objects to strings for output in PHP, you can use the magic method __toString() within the object's class definition. This method should return a string representation of the object that you want to output. By implementing this method, you can control how the object is converted to a string when it is echoed or concatenated in PHP.
class Example {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function __toString() {
return $this->name;
}
}
$object = new Example('John Doe');
echo $object; // Output: John Doe