Blogger Information
Blog 17
fans 0
comment 0
visits 12607
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
面向接口编程(包括trait)学习心得
越努力越幸运
Original
588 people have browsed it

//作业

     //接口及trait的面向接口编程学习心得:

    

     //接口:特殊的抽象类;特点:1.成员属性只能是常量,不能是变量;

     //2.所有方法都只能是抽象方法;

     //3.可以在实现时,多继承;

    

     interface iGoods{

     const SERIAL=10;

    

     function fun1();

     function fun2();

     }

    

     interface iGoods1{

     const NAME='垫圈';

    

     function fun3();

     }

    

     class Goodslist implements iGoods,iGoods1{

    

     function fun1(){

     echo iGoods::SERIAL.'<br>';

     }

     function fun2(){

     echo iGoods1::NAME.'<br>';

     }

     function fun3(){

     echo iGoods::SERIAL.':'.iGoods1::NAME.'<br>';

     }

     }

    

     $goods=new Goodslist();

     echo $goods->fun3();

//trait:不能有类常量

     trait A{

     public $x=100;

     protected $name='胡八一';

     public function get(){

     return $this->name;

     }

    

     public static $y=2;

     public static function set(){

     return self::$y;

    

     }

     public static $age;

    

     abstract public static function set1();

     }

    

     //客户端:

     class User3{

     //在类中使用trait,用use关键字

     use A;

     //使用trait,像接口一样,必须实现抽象方法,否则报错

     public static function set1(){

     return self::$age;

     }

     }

    

     $user3=new User3();

     User3::$age=49;

    

     echo $user3->get().':'. User3::set1();

     echo '<br>';

    

     //所以,trait最好的地方是,可以写一个方法,方便地在很多需要的类中使用;

     //trait中的属性不允许被重写;同时:trait的属性不允许重名;

     //trait的方法和继承上下文中的重名方法优先级:

     //子类(当前类)>trait>父类;

     //方法集:在父类和子类间,定义很多trait,来实现父类和子类原本方法的不足;

    

    

    

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