美文网首页
MS-特性-Trait

MS-特性-Trait

作者: Captain_tu | 来源:发表于2019-01-03 18:38 被阅读0次
  1. Trait (PHP5.4+)

Trait可以看做类的部分实现,可以混入一个或多个现有的PHP类中。
其作用有两个:表明类可以做什么;提供模块化实现。
Trait是一种代码复用技术,为PHP的单继承限制提供了一套灵活的代码复用机制

class biology{
    public $name;
    public function __construct($name)
    {
        $this->name = $name;
    }

    public function eat() {
        echo "Biology can eat"."<br>";
    }
}

trait all_common{
    function walk() {
        echo "$this->name can walk"."<br>";
    }
    
    /**
     * 覆盖父类继承的eat方法
     */
    function eat() {
        echo "$this->name can eat"."<br>";
    }
}

trait animal_common{
    function speak() {
        echo "$this->name can speak"."<br>";
    }
}

trait bird_common{
    function fly() {
        echo "$this->name can fly"."<br>";
    }
}

class people extends biology {
    use all_common;
    use animal_common;
    public function __construct($name)
    {
        parent::__construct($name);
    }

    public function smart() {
        echo "$this->name am very smarty"."<br>";
    }
}

class eagle extends biology {
    use all_common;
    use bird_common;
    public function __construct($name)
    {
        parent::__construct($name);
    }

    public function wing() {
        echo "$this->name have wings"."<br>";
    }

    /**
     * 覆盖trait中的eat方法
     */
    public function eat() {
        echo "I am a $this->name, I can eat"."<br>";
    }
}

$p = new people("People");
$b = new eagle("Eagle");
$p->walk();
$b->walk();
$p->speak();
$b->fly();
$p->smart();
$b->wing();
$p->eat();
$b->eat();
  • Trait的优先级
    自身定义的方法>Trait的方法>父类继承的方法
    优先级高的,会覆盖优先级低的方法
    use多个Trait中不能含有同名方法

相关文章

  • MS-特性-Trait

    Trait (PHP5.4+) Trait可以看做类的部分实现,可以混入一个或多个现有的PHP类中。其作用有两个:...

  • Rust impl trait

    trait特性 trait特性可以理解为Java中的接口,具备和接口很类似的特性。trait中的函数叫做方法。某个...

  • Trait特性

    PHP5.4以后实现了一个新的代码复用的方法Trait,Trait为了减少单继承语言的限制,相对于传统继承增加了水...

  • 那些永远记不住的单词| Trait 特性品质【127】

    Trait 英 [treɪt; treɪ] 美 [tret] n. 特性,特点;品质;少许 n. (Trait)...

  • php trait 特性

    trait 特性总结 : 使用关键字 : use / as / insteadof 属性: 不允许在继承的 tra...

  • 同义词整理

    人的特性,品质 character trait idiosyncrasy ['ɪdɪə(ʊ)'sɪŋkrəsɪ] ...

  • Adaptive Layout

    设备适配手段 Trait(设备特性)iOS 8+ UITraitEnvironment protocol(UISc...

  • PHP基础( php7新特性 )

    严格模式( 函数 ) 匿名类 trait 特性 上传文件参考地址 : https://www.cnblogs...

  • MS-特性-PHP7

    标量类型声明,返回值类型声明 declare(strict_types=1); //开启强制类型模式 cla...

  • Laravel中的Trait特性

    相对于多继承语言(如C++),代码复用这个问题对于单继承类语言(如Ruby、PHP等)来说需要通过其他方法来解决,...

网友评论

      本文标题:MS-特性-Trait

      本文链接:https://www.haomeiwen.com/subject/stlqrqtx.html