php中介面與抽象類別區別及如何定義和繼承介面執行個體代碼詳解

來源:互聯網
上載者:User
抽象類別和介面的區別

介面是特殊的抽象類別,也可以看做是一個模型的規範。介面與抽象類別大致區別如下:

一個子類如果 implements 一個介面,就必須實現介面中的所有方法(不管是否需要);如果是繼承一個抽象類別,只需要實現需要的方法即可。

如果一個介面中定義的方法名改變了,那麼所有實現此介面的子類需要同步更新方法名;而抽象類別中如果方法名改變了,其子類對應的方法名將不受影響,只是變成了一個新的方法而已(相對老的方法實現)。

抽象類別只能單繼承,當一個子類需要實現的功能需要繼承自多個父類時,就必須使用介面。

程式碼範例:

<?php//簡單定義實現介面interface UserInterface{  //定義user介面    function getname();}interface TeacherInterface{    //定義teacher介面    function getLengthofService();}class User implements UserInterface{ //實現user介面    private $name="nostop";    public function getName(){        return $this->name;    }}class Teacher implements TeacherInterface{ //實現teacher介面    private $age=23;    public function getLengthofService(){        return $this->age;    }}$user=new User();echo $user->getName().'<br />';//nostop$teacher=new Teacher();echo $teacher->getLengthofService().'<br />';//23//繼承類實現介面class GraduResultudent extends User implements TeacherInterface{ //繼承User類 實現介面    private $teacher;    public function construct(){     //定義建構函式        $this->teacher=new Teacher();  //執行個體化Teacher對象    }    public function getLengthOfService(){ //實現TeacherInterface介面的方法        return $this->teacher->getLengthOfService();    }}class Result{    public static function getUserName(UserInterface $_user){ //注意:這裡面的類型變成介面類型        echo "Name is ".$_user->getName().'<br />';    }    public static function getLengthOfService(TeacherInterface $_teacher){ //注意:這裡面的類型變成介面類型        echo "age is ".$_teacher->getLengthOfService();    }}$object=new GraduResultudent();Result::getUserName($object); //Name is nostopResult::getLengthOfService($object); //age is 23echo "<br />";//介面實現使用者的折扣interface People{    //定義介面    function getUserType();    function getCount();}class VipUser implements People{ //實現介面    //使用者折卡係數    private $discount=0.8;    function getUserType(){        return "VIP使用者";    }    function getCount(){        return    $this->discount;           }}$vip=new VipUser();    //實現化對象echo $vip->getUserType().'商品價格:'.$vip->getCount()*100;  //VIP使用者商品價格:80class Goods{    var $price=100;    var $member;    function run(People $member){ //注意:這裡面的參數類型是介面類型        $this->member=$member;        $discount=$this->member->getCount();        $usertype=$this->member->getUserType();        echo $usertype."商品價格:".$this->price*$discount;    }}$display=new Goods();$display->run(new VipUser);//VIP使用者商品價格:80?>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.