PHP接口

PHP接口

PHP接口(interface)做用相似於繼承中的父類,接口是用於給其餘的類繼承用的,可是接口中定義的方法都是沒有方法體的且定義的方法必須是公有的。
舉例:php

<?php
    interface iTemplate{
        public function eat($food);
        public function learn($code);
    }
    class student implements iTemplate{
        public function eat($food){
            echo "student eat {$food}";
        }
        public function learn($code){
            echo "student learn {$code}";
        }
    }
    $student = new student();
    $student->eat('apple');
    echo '<br />';
    $student->learn('PHP');
?>

輸出:app

student eat apple
student learn PHP

接口中除了方法也是能夠定義屬性的,但必須是常量。code

<?php
    interface iTemplate{
        public function eat($food);
        public function learn($code);
        const A='我是常量';
    }
    class student implements iTemplate{
        public function eat($food){
            echo "student eat {$food}";
        }
        public function learn($code){
            echo "student learn {$code}";
        }
        public function changliang(){
            echo ITemplate::A;
        }

    }
    $student = new student();
    $student->eat('apple');
    echo '<br />';
    $student->learn('PHP');
    echo '<br />';
    $student->changliang();
?>

輸出:繼承

student eat apple
student learn PHP
我是常量

那麼既然是定義給其餘類使用,就存在繼承的問題,接口是能夠多繼承的。
舉例:接口

<?php
    interface iTemplate1{
        public function eat($food);
    }
    interface iTemplate2{
        public function learn($code);
    }
    class student implements iTemplate1,iTemplate2{
        public function eat($food){
            echo "student eat {$food}";
        }
        public function learn($code){
            echo "student learn {$code}";
        }
    }
    $student = new student();
    $student->eat('apple');
    echo '<br />';
    $student->learn('PHP');
?>

輸出:io

student eat apple
student learn PHP

這樣就在student類中繼承了iTemplate1iTemplate2接口,話能夠先讓iTemplate2接口繼承iTemplate1接口,再讓student類去繼承iTemplate1接口,實現的效果同上。
舉例:function

<?php
    interface iTemplate1{
        public function eat($food);
    }
    interface iTemplate2 extends iTemplate1{
        public function learn($code);
    }
    class student implements iTemplate2{
        public function eat($food){
            echo "student eat {$food}";
        }
        public function learn($code){
            echo "student learn {$code}";
        }
    }
    $student = new student();
    $student->eat('apple');
    echo '<br />';
    $student->learn('PHP');
?>

輸出:class

student eat apple
student learn PHP

總結一下:方法

  • 接口不能實例化
  • 接口中的方法不能有方法體
  • 繼承接口的方法必須實現接口中的全部方法
  • 一個類能夠繼承多個接口
  • 接口中的屬性必須是常量
  • 接口中的方法必須是public(默認public)

不對的地方還望dalao們指正。im

相關文章
相關標籤/搜索