萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP __toString() 魔術方法:物件字串化的最佳實踐

核心概念

__toString() 是 PHP 物件導向中的魔術方法,當嘗試將物件直接當作字串輸出(如 echo $obj 或字串串接)時自動觸發。若類別未定義此方法,PHP 會拋出 Catchable fatal error: Object of class X could not be converted to string。

基本語法規則

  • 必須宣告為 public
  • 必須回傳 字串(return 字串值)
  • 不可拋出異常(會導致致命錯誤)
public function __toString(): string

基礎範例

定義 __toString() 的類別

<?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
?>

未定義 __toString() 的後果

<?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
?>

實際應用場景

1. 除錯與日誌記錄

<?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']
?>

2. 模板引擎整合

<?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
?>

3. 值物件表示

<?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 回傳等場景自然融入字串上下文。記住:永遠回傳字串、永遠公開可見、避免副作用,即能寫出優雅且健壯的程式碼。

copyright © 萬盛學電腦網 all rights reserved