一,接口的定義和調(diào)用
1 <?php 2 interface face1 3 { 4 const param = 'test'; 5 public function show(); 6 } 7 8 class test implements face1 9 {10 public function show()11 {12 echo "interface is run<br>";13 }14 }15 16 $face = new test();17 echo $face->show(); //inerface is run18 echo face1::param; //test19 ?>
說明:上面的例子要注意一點,接口的方法名是show,繼承接口的類中必須有show這個方法,要不然就會報錯。也就是說接口的方法是假的,真正起作用的是在繼承的類中的方法,就是因為這一點,所以我覺得,接口根php的抽象類有點像。
二,對參數(shù)約束比較嚴
<?phpinterface face1{ public function show(show $show);}// 顯示正常class test implements face1{ public function show(show $show) { echo "asdfasdf"; }}// 報fatal錯誤class test2 implements face1{ public function show(aaa $aaa) { }}?>
說明:上面的這個例子報fatal錯誤的,為什么會報fatal錯誤呢?原因就在所傳參數(shù)是aaa $aaa,而不是show $show。繼承接口類中,調(diào)用接口的方法時,所傳參數(shù)要和接口中的參數(shù)名要一至。不然就會報錯。
三,接口間的繼承和調(diào)用接口傳遞參數(shù)
<?phpinterface face1{ public function show();}interface face2 extends face1{ public function show1(test1 $test,$num);}class test implements face2{ public function show() { echo "ok<br>"; } public function show1(test1 $test,$num) { var_dump($test); echo $test1->aaaa."$num<br>"; }}class test1{ public $aaaa="this is a test"; function fun(){ echo ' ===============<br>'; }}$show = new test1;$show->fun(); //顯示===============test::show(); //顯示oktest::show1($show,6); //object(test1)#1 (1) { ["aaaa"]=> string(14) "this is a test" } 6?>
說明:上面的例子可以看到,接口face2繼承了接口face1,類test繼承了接口face2。不知道你發(fā)現(xiàn)沒有,class類test當中包括有二個方法,一個是show,一個show1,并且一個也不能少,如果少一個,報fatal錯誤。show1(test1 $test,$num)中的test1必須根繼承類的名子要一樣classtest1。如果不一樣,也會報fatal錯誤。那如果一個接口被多個類繼承,并且類名又不一樣,怎么辦呢?那就要用self了,下面會提到
四,一個接口多個繼承
<?phpinterface Comparable { function compare(self $compare);}class String implements Comparable { private $string; function __construct($string) { $this->string = $string; } function compare(self $compare) { if($this->string == $compare->string){ return $this->string."==".$compare->string."<br>"; }else{ return $this->string."!=".$compare->string."<br>"; } }}class Integer implements Comparable { private $integer; function __construct($int) { $this->integer = $int; } function compare(self $compare) { if($this->integer == $compare->integer){ return $this->integer."==".$compare->integer."<br>"; }else{ return $this->integer."!=".$compare->integer."<br>"; } }}$first_int = new Integer(3);$second_int = new Integer(4);$first_string = new String("foo");$second_string = new String("bar");echo $first_int->compare($second_int); // 3!=4echo $first_int->compare($first_int); // 3==3echo $first_string->compare($second_string); // foo!=barecho $first_string->compare($second_int); // 嚴重錯誤?>
說明:從上面的例子中可以看出,一個接口可以被多個類繼承,并且類名不一樣。同一個類之間可以相互調(diào)用,不同類之間不能調(diào)用。echo $first_string->compare($second_int);報fatal錯誤的。