php中的trait

来源:互联网 发布:java九九乘法表编程 编辑:程序博客网 时间:2024/06/05 15:52

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中的方法

0 0
原创粉丝点击