php 設計模式 之 interface 介面簡介

來源:互聯網
上載者:User
須知
  • 與大多數抽象類別一樣,interface 也有抽象方法,不管不能和抽象類別一樣在介面中包含具體的方法或變數(做為抽象性的例外)
  • 一般約定介面總以字母 I 或者 i 開頭
  • 介面中定義的所有方法都必須是public,這是介面的特性
  • 實現多個介面時,介面中的方法不能有重名。
  • 介面也可以繼承,通過使用 extends 操作符。
  • 類要實現介面,必須使用和介面中所定義的方法完全一致的方式。否則會導致致命錯誤。
  • 介面中也可以定義常量。介面常量和類常量的使用完全相同,但是不能被子類或子介面所覆蓋。
  • 理解

    PHP介面類interface就是一個類的領導者,指明方向,子類必須完成它指定方法

    簡單代碼示範

    /** * interface 介面 * 與大多數抽象類別一樣,interface 也有抽象方法,不管不能和抽象類別一樣在介面中包含具體的方法或變數(做為抽象性的例外) * 一般約定介面總以字母 I 或者 i 開頭 * 介面中定義的所有方法都必須是public,這是介面的特性 */// 定義一個介面類,以 interface 開頭而不是 classinterface ISMS{ // 可以定義常量 const USERNAME = 'hhh'; // 定義的方法,子類必須實現 public function getInfo($info); public function sendInfo($info);}// 實現一個介面,使用 implements 而不是 extendsclass Register implements ISMS{ // 使用介面常量,需要用 範圍解析操作符 private $username = ISMS::USERNAME; public function getInfo($info){ return 'getInfo=>'.$info; } public function sendInfo($info){ return 'sendInfo=>'.$info; } public function getUserName(){ return $this->username; }}$test = new Register();echo $test->getInfo('Enda'); // getInfo=>Endaecho $test->sendInfo('Enda'); // sendInfo=>Endaecho $test->getUserName(); // hhh
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.