如何在 PHP 中連結方法?


變異器方法可用於連結方法,其中這些方法返回原始物件,並且可以呼叫對這些透過變異器函式返回的物件執行的其他方法。

示例

以下是一個演示相同功能的簡單示例 −

Live Demo

<?php
class sample_class {
   private $str;
   function __construct() {
      $this->str = "";
   }
   function addA() {
      $this->str .= "am";
      return $this;
   }
   function addB() {
      $this->str .= "_bn";
      return $this;
   }
   function getStr() {
      return $this->str;
   }
}
$new_object = new sample_class();
echo $new_object->addA()->addB()->getStr();

輸出

這會產生以下輸出 −

am_bn

更新於: 06-04-2020

1K+ 瀏覽

開始你的 職業

完成課程後獲得認證

開始
廣告
© . All rights reserved.