主要對類名,類所擁有的方法,以及所傳參數起約束和規范做用,感覺跟php abstract 抽象類又有點像。
一,接口的定義和調用
- <?php
- interface face1
- {
- const param = 'test';
- public function show();
- }
- class test implements face1
- {
- public function show()
- {
- echo "interface is run<br>";
- }
- }
- $face = new test();
- echo $face->show(); //inerface is run
- echo face1::param; //test
- ?>
說明:上面的例子要注意一點,接口的方法名是show,繼承接口的類中必須有show這個方法,要不然就會報錯。也就是說接口的方法是假的,真正起作用的是在繼承的類中的方法,就是因為這一點,所以我覺得,接口根php的抽象類有點像。
二,對參數約束比較嚴
- <?php
- interface 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錯誤呢?原因就在所傳參數是aaa $aaa,而不是show $show。繼承接口類中,調用接口的方法時,所傳參數要和接口中的參數名要一至。不然就會報錯。
三,接口間的繼承和調用接口傳遞參數
- <?php
- interface 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(); //顯示ok
- test::show1($show,6); //object(test1)#1 (1) { ["aaaa"]=> string(14) "this is a test" } 6
- ?>
說明:上面的例子可以看到,接口face2繼承了接口face1,類test繼承了接口face2。不知道你發現沒有,class類test當中包括有二個方法,一個是show,一個show1,並且一個也不能少,如果少一個,報fatal錯誤。show1(test1 $test,$num)中的test1必須根繼承類的名子要一樣class test1。如果不一樣,也會報fatal錯誤。那如果一個接口被多個類繼承,並且類名又不一樣,怎么辦呢?那就要用self了,下面會提到
四,一個接口多個繼承
- <?php
- interface 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!=4
- echo $first_int->compare($first_int); // 3==3
- echo $first_string->compare($second_string); // foo!=bar
- echo $first_string->compare($second_int); // 嚴重錯誤
- ?>
說明:從上面的例子中可以看出,一個接口可以被多個類繼承,並且類名不一樣。同一個類之間可以相互調用,不同類之間不能調用。echo $first_string->compare($second_int);報fatal錯誤的。
