php中的trait

php是不支持多继承的,但是php中trait的使用可以做到类似多继承的效果(个人是这么觉得的),php 5.4.0以上版本支持trait

基本使用

<?php 
trait traitDemo{
  function getRand(){
    return rand(1,50);
  }
}


class demo1{
  public function get(){
    return 'demo';
  }
}


class demo2 extends demo1
{
  use traitDemo;
  public function gets(){
    echo $this->get(),$this->getRand();
  }
}

需要注意的是如果trait中的方法和基类的方法名一样,则会覆盖基类方法,当前类的方法名和trait中的方法一样,则会覆盖trait中的方法

猜你喜欢

转载自blog.csdn.net/chenbalala/article/details/52292783
今日推荐