Blogger Information
Blog 17
fans 0
comment 0
visits 12632
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait与接口/抽象类实战
越努力越幸运
Original
709 people have browsed it

//命名冲突和改变访问控制

     trait t8{

         public function say(){

              echo 'these are two method with the same name.';

         }

     }

     trait t9{

         protected function say(){

            echo 'these are two method with the same name.';

         }

     }

     trait t10{

         use t8,t9{

             t8::say insteadof t9;

             t9::say as public read;

         }

     }

     class work3{

        use t10;

     }

     $work3=new work3();

     echo $work3->say().'<br>';

     echo $work3->read().'<br>';


//trait和interface及class

     trait t11{

         public function aa($year){

             $age=2020-$year;

             return $age;

         }

     }

    

     interface i2{

         const NAME='jack';

         public function caculator(int $i);

     }

    

     class Work4 implements i2{

         use t11;

         public function caculator(int $i){

             if($i>0){

                 $sum=0;

                 for($j=0;$j<=$i;$j++){

                      $sum=$sum+$j;

                 }

                 return $sum;

              }else {

                  return '参数非法';

              }

          }

     }

     $work4=new Work4();

     echo '参数年份,计算年龄:<br>';

     echo $work4::NAME.'的年龄是:'.$work4->aa(2000).'<br>';

     echo '参数正整数,进行累加:<br>';

     echo '结果是'.$work4->caculator(10).'<br>';

    

    //trait的理解:一些方法和常量打包在trait里面,在类中使用时,use一下就能用,

    //优点:省去了父类/子类和继承,以及访问控制这些麻烦(trait中都是public);

    //缺点:a.方法都是public,不能访问限制;b.由于trait可以use 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