本文實(shí)例講述了PHP 對(duì)象接口簡單實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
對(duì)象接口 (interface)
使用接口(interface),可以指定某個(gè)類必須實(shí)現(xiàn)哪些方法,但不需要定義這些方法的具體內(nèi)容。
接口是通過 interface 關(guān)鍵字來定義的,就像定義一個(gè)標(biāo)準(zhǔn)的類一樣,但其中定義所有的方法都是空的。
接口中定義的所有方法都必須是公有,這是接口的特性。
實(shí)現(xiàn)(implements)
要實(shí)現(xiàn)一個(gè)接口,使用 implements 操作符。類中必須實(shí)現(xiàn)接口中定義的所有方法,否則會(huì)報(bào)一個(gè)致命錯(cuò)誤。類可以實(shí)現(xiàn)多個(gè)接口,用逗號(hào)來分隔多個(gè)接口的名稱。
Note:
實(shí)現(xiàn)多個(gè)接口時(shí),接口中的方法不能有重名。
Note:
接口也可以繼承,通過使用 extends 操作符。
Note:
類要實(shí)現(xiàn)接口,必須使用和接口中所定義的方法完全一致的方式。否則會(huì)導(dǎo)致致命錯(cuò)誤。
示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?php // 聲明一個(gè)'iTemplate'接口 interface iTemplate { public function setVariable( $name , $var ); public function getHtml( $template ); } // 實(shí)現(xiàn)接口 // 下面的寫法是正確的 class Template implements iTemplate { private $vars = array (); public function setVariable( $name , $var ) { $this ->vars[ $name ] = $var ; } public function getHtml( $template ) { foreach ( $this ->vars as $name => $value ) { $template = str_replace ( '{' . $name . '}' , $value , $template ); } return $template ; } } |
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
原文鏈接:https://www.cnblogs.com/ryanzheng/p/11404710.html