php trait 模拟多继承

php是一种单一继承的语言,trait能解决这一代码重用的问题,它能让开发者在多个不同的class中实现代码重用

用法

trait 定义类
use 使用

模拟多继承实例

<?php

trait Animal {
    public function run(){
        echo 'animal run'."<br>";
    }

    public function jump(){
        echo 'animal jump'."<br>";
    }
}

trait Human {
    public function study(){
        echo 'human study'."<br>";
    }
}


class Person{
    use Animal, Human;

    //方法重名使用别名方式
    //use Animal, Human{
    //    Animal::run as AnimalRun;
    //}

    public $name;

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

    public function build(){
        echo 'person build'."<br>";
    }
}

//创建对象
$person = new Person('胡勇健');
$person->run();
$person->jump();
$person->study();
$person->build();

结果显示

animal run
animal jump
human study
person build