PHP 8 中的 Stringable 介面是什麼?


在 PHP 8 中,添加了新的 Stringable 介面(__toSting)。此方法以雙下劃線(__)開頭。__toString 方法允許將物件表示為字串。當一個類使用 __toString 定義方法時,每當它需要作為字串處理時,它將呼叫一個物件。

示例:使用 __toString 的 Stringable 介面

 線上演示

<?php
   class Employee{
      public function __toString(): string
      {
         return 'Employee Name';
      }
   }
   $employee = new Employee();
   print_r((string)$employee);
?>

輸出

Employee Name

在 PHP 8 中,Stringable 介面使得傳遞字串變得容易。當一個類實現了 __toString 方法後,會自動新增一個Stringable 介面。它不需要顯式實現介面。只要在施加嚴格型別(string_types=1)時,Stringable 介面對於型別提示就很有用。

示例:在 PHP 8 中使用 Stringable 介面

 線上演示

<?php
   declare(strict_types=1);
   class Employee {
      public function __toString() {
         return 'Employee Details';
      }
   }
   $emp = new Employee;
   var_dump($emp instanceof Stringable);
?>

輸出

bool(true)

更新於: 2021 年 4 月 1 日

361 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始
廣告
© . All rights reserved.