__toString() 是 PHP 物件導向中的魔術方法,當嘗試將物件直接當作字串輸出(如 echo $obj 或字串串接)時自動觸發。若類別未定義此方法,PHP 會拋出 Catchable fatal error: Object of class X could not be converted to string。
publicreturn 字串值)public function __toString(): string
<?php
class TestClass {
public $foo;
public function __construct($foo) {
$this->foo = $foo;
}
public function __toString(): string {
return $this->foo;
}
}
$class = new TestClass('Hello');
echo $class; // 直接輸出物件,自動呼叫 __toString() → 輸出:Hello
?>
<?php
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function say() {
echo "Hello, {$this->name}!<br/>";
}
}
$wblog = new Person('WBlog');
echo $wblog; // Catchable fatal error: Object of class Person could not be converted to string
?>
<?php
class User {
private $id;
private $name;
private $email;
public function __construct($id, $name, $email) {
$this->id = $id;
$this->name = $name;
$this->email = $email;
}
public function __toString(): string {
return sprintf(
"User[id=%d, name='%s', email='%s']",
$this->id, $this->name, $this->email
);
}
}
$user = new User(1, '張三', 'zhang@example.com');
error_log("用戶登入: " . $user); // 直接串接物件,自動格式化
// 日誌輸出:用戶登入: User[id=1, name='張三', email='zhang@example.com']
?>
<?php
class ViewModel {
private $data = [];
public function __set($key, $value) {
$this->data[$key] = $value;
}
public function __toString(): string {
// 簡易模板渲染
extract($this->data);
ob_start();
include __DIR__ . '/template.php';
return ob_get_clean();
}
}
// 使用方式
$view = new ViewModel();
$view->title = '歡迎頁面';
$view->user = '訪客';
echo $view; // 直接輸出渲染後的 HTML
?>
<?php
class Money {
private $amount;
private $currency;
public function __construct(float $amount, string $currency = 'TWD') {
$this->amount = $amount;
$this->currency = strtoupper($currency);
}
public function __toString(): string {
return number_format($this->amount, 2) . ' ' . $this->currency;
}
public function add(Money $other): Money {
if ($this->currency !== $other->currency) {
throw new InvalidArgumentException('幣別不相符');
}
return new Money($this->amount + $other->amount, $this->currency);
}
}
$price = new Money(1299.99);
$tax = new Money(78.00);
$total = $price->add($tax);
echo "總計: $total"; // 總計: 1,377.99 TWD
?>
<?php
interface Stringable {
public function __toString(): string;
}
class Report implements Stringable {
// 強制實作 __toString()
public function __toString(): string {
return "報表內容...";
}
}
function printReport(Stringable $report) {
echo $report; // 類型提示保證可字串化
}
?>
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
| 回傳非字串 | 回傳陣列/物件/整數 | 強制轉字串 return (string)$value |
| 拋出例外 | 觸發 Fatal Error | 回傳錯誤訊息字串或空字串 |
| 宣告為 private/protected | 無法被外部觸發 | 必須 public |
| 執行重度運算 | 影響效能(每次字串轉換都會執行) | 快取結果或簡化邏輯 |
__toString() 是物件字串化的標準介面,善用它能讓物件在日誌、模板、API 回傳等場景自然融入字串上下文。記住:永遠回傳字串、永遠公開可見、避免副作用,即能寫出優雅且健壯的程式碼。