首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP __toString() 魔術方法:讓物件直接輸出字串

     編輯:PHP 相關知識

為什麼需要 __toString()?

在 PHP 中,直接 echo $object 會觸發 Catchable fatal error: Object of class ... could not be converted to string。因為物件是複雜資料結構,PHP 不知道該如何將其轉為字串。__toString() 正是解決此問題的魔術方法——當物件被視為字串使用時自動呼叫。

基本語法與規則

  • 方法必須宣告為 public
  • **必須回傳字串**(return),否則會觸發錯誤
  • PHP 5.2.0+ 支援於任何字串語境(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() 讓物件具備「字串表現形式」,極大提升除錯效率、日誌可讀性與模板輸出便利性。記住:**永遠回傳字串、不要拋出例外、善用於格式化輸出**。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved