Blogger Information
Blog 17
fans 0
comment 0
visits 12549
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
继承/抽象与接口学习心得
越努力越幸运
Original
875 people have browsed it

//demo03

    class User2{//作业

     protected $name='胡八一';

     protected $age=40;

     private $salary=9999;

     protected static $nationality='中国/CHINA';

    

     public function write2(){

     return "姓名:{$this->name},年龄:{$this->age}";

     }

    }

    

    class Bob2 extends User2{

     protected $age=50;//重写

     //方法重写:方法级的多态:

     /*

     public function write2(){

     return "姓名:{$this->name},年龄:{$this->age},is an American";

     }

     */

     public function write3(){

     return parent::write2().',is an American~';

     }

    

     //扩展

     protected $profession='teacher';

     public function write4(){

     return parent::write2().",职业:{$this->profession}";

     }

    }

    

    $bob2=new Bob2();

    echo $bob2->write3().'<br>';//继承和重写;

    echo $bob2->write4().'<br>';//扩展;


//抽象

//demo05:抽象类不能实例化

    //有了抽象类,就可以实现设计类和工作类分离;

    //抽象类:是设计类;

    abstract class User3{

     protected $name='胡八一';

     protected $age=40;

    

     protected function write5(){

     return "姓名:{$this->name},年龄:{$this->age}";

     }

    

     //没有方法体:叫做抽象方法

     //只要有一个抽象方法,这个类叫抽象类

     abstract protected function write6();

    

    

    }

    

    //继承了抽象类,就是工作类

    class Bob3 extends User3{

     protected $profession='teacher';

     //必须将抽象类中的抽象方法实现

     public function write6(){

     return parent::write5().",职业:{$this->profession}";

     }

    }

    

    $bob3=new Bob3();

    echo $bob3->write6();

    echo '<br>';

    

//demo06

//接口:彻底分离


    //关键字:inteface

    //使用与类相似的语法:抽象方法,常量,构造方法

    //默认访问控制必须是public

    //接口允许多继承,从而间接实现了php的多继承

    //接口类方法默认是抽象方法,所以可以省略abstract ;

    

    

    //implements 

    interface Aaa{

     const NATION='中国';

    

     public static  function write7();

    }

    

    class User4 implements Aaa{

     protected static $name='胡八一';

     public static function write7(){

     return self::$name.'的国籍是:'.Aaa::NATION;

     }

    }

    

    echo User4::write7();

    

    

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post