PHP鎺ュ彛
浣跨敤鎺ュ彛锛坕nterface锛夛紝浣犲彲浠ユ寚瀹氭煇涓被蹇呴』瀹炵幇鍝簺鏂规硶锛屼絾涓嶉渶瑕佸畾涔夎繖浜涙柟娉曠殑鍏蜂綋鍐呭銆
鎴戜滑鍙互閫氳繃interface鏉ュ畾涔変竴涓帴鍙o紝灏卞儚瀹氫箟涓涓爣鍑嗙殑绫讳竴鏍凤紝浣嗗叾涓畾涔夋墍鏈夌殑鏂规硶閮芥槸绌虹殑銆
鎺ュ彛涓畾涔夌殑鎵鏈夋柟娉曢兘蹇呴』鏄痯ublic锛岃繖鏄帴鍙g殑鐗规с
瀹炵幇
瑕佸疄鐜颁竴涓帴鍙o紝鍙互浣跨敤implements鎿嶄綔绗︺傜被涓繀椤诲疄鐜版帴鍙d腑瀹氫箟鐨勬墍鏈夋柟娉曪紝鍚﹀垯 浼氭姤涓涓猣atal閿欒銆傚鏋滆瀹炵幇澶氫釜鎺ュ彛锛屽彲浠ョ敤閫楀彿鏉ュ垎闅斿涓帴鍙g殑鍚嶇О銆
Note:
瀹炵幇澶氫釜鎺ュ彛鏃讹紝鎺ュ彛涓殑鏂规硶涓嶈兘鏈夐噸鍚嶃
Note:
鎺ュ彛涔熷彲浠ョ户鎵匡紝閫氳繃浣跨敤extends鎿嶄綔绗︺
甯搁噺
鎺ュ彛涓篃鍙互瀹氫箟甯搁噺銆傛帴鍙e父閲忓拰绫诲父閲忕殑浣跨敤瀹屽叏鐩稿悓銆 瀹冧滑閮芥槸瀹氬硷紝涓嶈兘琚瓙绫绘垨瀛愭帴鍙d慨鏀广
鑼冧緥
Example #1 鎺ュ彛浠g爜绀轰緥
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<span style="font-size:14px;"><code><?php
// 澹版槑涓涓'iTemplate'鎺ュ彛
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
// 瀹炵幇鎺ュ彛
// 涓嬮潰鐨勫啓娉曟槸姝g‘鐨
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;
}
}
// 涓嬮潰鐨勫啓娉曟槸閿欒鐨勶紝浼氭姤閿欙細
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
}
?></code></span>
|
Example #2 Extendable Interfaces
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
30
31
32
33
34
35
|
<span style="font-size:14px;"><code><?php
interface a
{
public function foo();
}
interface b extends a
{
public function baz(Baz $baz);
}
// 姝g‘鍐欐硶
class c implements b
{
public function foo()
{
}
public function baz(Baz $baz)
{
}
}
// 閿欒鍐欐硶浼氬鑷翠竴涓猣atal error
class d implements b
{
public function foo()
{
}
public function baz(Foo $foo)
{
}
}
?></code></span>
|
Example #3 澶氫釜鎺ュ彛闂寸殑缁ф壙
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
30
31
|
<span style="font-size:14px;"><code>
}
}
{
public function baz()
}
{
public function bar()
}
{
public function foo()
{
class d implements c
}
public function baz();
{
interface c extends a, b
}
public function bar();
{
interface b
}
public function foo();
{
interface a
<?php</code></span>
|
Example #4 浣跨敤鎺ュ彛甯搁噺
1
2
3
4
5
6
|
<span style="font-size:14px;"><code>
}
const b = 'Interface constant';
{
interface a
<?php</code></span>
|
// 杈撳嚭鎺ュ彛甯搁噺
1
|
<span style="font-size:14px;">echo a::b;</span>
|
// 閿欒鍐欐硶锛屽洜涓哄父閲忕殑鍊间笉鑳借淇敼銆傛帴鍙e父閲忕殑姒傚康鍜岀被甯搁噺鏄竴鏍风殑銆
1
2
3
4
5
|
<span style="font-size:14px;"><code>class b implements a
{
const b = 'Class constant';
}
?></code></span>
|
浠ヤ笂灏辨槸PHP鎺ュ彛鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒