Blogger Information
Blog 56
fans 3
comment 1
visits 50691
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait实例——2018年5月8日
沈斌的博客
Original
584 people have browsed it

PHP中trait的使用实现多继承,有同名方法,优先级 子类>trait>父类


实例

<?php
/**
 *
 */
class Mobile {
    private $name;
    public function __construct($name)
    {
        $this->name=$name;
    }

    public function call($num='180') {
        return $this->name.'call:'.$num;
    }
}

trait Xiaomi {
    private $name='Xiaomi';

    public function call($num='189'){
        return $this->name.' call:'.$num;
    }
}
class Apple extends Mobile {

    use Xiaomi;

    public function __construct($name)
    {
        parent::__construct($name);
    }

//    public function call($num = '188')
//    {
//       return $this->name.' call:'.$num;
//    }

}

$apple=new Apple('apple');
echo $apple->call();

运行实例 »

点击 "运行实例" 按钮查看在线实例

输出trait的方法 Xiaomi call:188

Correction status:qualified

Teacher's comments:
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