__toString() 是魔術方法的一種,具體用途是當一個對象被當作字符串對待的時候,會觸發這個魔術方法 以下說明摘自PHP官方手冊
public string __toString ( void )
__toString() 方法用於一個類被當成字符串時應怎樣回應。例如 echo $obj; 應該顯示些什么。此方法必須返回一個字符串,否則將發出一條 E_RECOVERABLE_ERROR
級別的致命錯誤。
Warning
不能在 __toString() 方法中拋出異常。這么做會導致致命錯誤。
Example #2 簡單示例
<?php // Declare a simple class class TestClass { public $foo; public function __construct($foo) { $this->foo = $foo; } public function __toString() { return $this->foo; } } $class = new TestClass('Hello'); echo $class; ?>
以上例程會輸出:
Hello
需要指出的是在 PHP 5.2.0 之前,__toString() 方法只有在直接使用於 echo 或 print 時才能生效。PHP 5.2.0 之后,則可以在任何字符串環境生效(例如通過 printf(),使用 %s 修飾符),但不能用於非字符串環境(如使用 %d 修飾符)。自 PHP 5.2.0 起,如果將一個未定義 __toString() 方法的對象轉換為字符串,會產生 E_RECOVERABLE_ERROR
級別的錯誤。