在 PHP 中,直接 echo $object 會觸發 Catchable fatal error: Object of class ... could not be converted to string。因為物件是複雜資料結構,PHP 不知道該如何將其轉為字串。__toString() 正是解決此問題的魔術方法——當物件被視為字串使用時自動呼叫。
publicreturn),否則會觸發錯誤printf()、字串串接等)<?php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function __toString() {
return "Hello, {$this->name}!";
}
public function say() {
echo "Hello, {$this->name}!<br>";
}
}
$user = new Person('WBlog');
echo $user; // 自動呼叫 __toString() 輸出:Hello, WBlog!
echo "<br>";
$user->say(); // 手動呼叫方法輸出:Hello, WBlog!
?>
<?php
class Order {
private $id;
private $items = [];
private $total = 0;
public function __construct($id) {
$this->id = $id;
}
public function addItem($name, $price, $qty = 1) {
$this->items[] = compact('name', 'price', 'qty');
$this->total += $price * $qty;
}
public function __toString() {
$output = "Order #{$this->id}\n";
foreach ($this->items as $item) {
$output .= "- {$item['name']} x{$item['qty']} @ ${$item['price']}\n";
}
$output .= "Total: \${$this->total}";
return $output;
}
}
$order = new Order(1001);
$order->addItem('Laptop', 1200);
$order->addItem('Mouse', 25, 2);
// 直接輸出物件即可獲得格式化訂單資訊
error_log((string)$order); // 寫入日誌檔
echo "<pre>" . $order . "</pre>"; // 網頁顯示
?>
| 錯誤情況 | 原因 | 解決方法 |
|---|---|---|
| 忘記實作 __toString() | 直接 echo 物件 | 在類別中實作 public function __toString() |
| 回傳非字串值 | return $this->name (若為整數) | 強制轉型:return (string)$this->name |
| 拋出例外而非回傳 | 方法中 throw new Exception | __toString() 不允許拋出例外,需回傳字串 |
__toString() 讓物件具備「字串表現形式」,極大提升除錯效率、日誌可讀性與模板輸出便利性。記住:**永遠回傳字串、不要拋出例外、善用於格式化輸出**。