PHP之trait的用法

万能青年
2022-03-07 / 0 评论 / 87 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年07月10日,已超过594天没有更新,若内容或图片失效,请留言反馈。

trait

<?php
trait Dog{
    public $name="dog";
    public function bark(){
        echo "This is dog";
    }
}
class Animal{
    public function eat(){
        echo "This is animal eat";
    }
}
class Cat extends Animal{
    use Dog;
    public function drive(){
        echo "This is cat drive";
    }
}
$cat = new Cat();
$cat->drive();
echo "<br/>";
$cat->eat();
echo "<br/>";
$cat->bark();


输出结果为:

This is cat drive

This is animal eat

This is dog

?>
优先级#1

<?php
class Base {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait SayWorld {
    public function sayHello() {
        parent::sayHello();
        echo 'World!';
    }
}

class MyHelloWorld extends Base {
    use SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

结果为

Hello World!

优先级#2
<?php
trait HelloWorld {
    public function sayHello() {
        echo 'Hello World!';
    }
}

class TheWorldIsNotEnough {
    use HelloWorld;
    public function sayHello() {
        echo 'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
?>

结果为

Hello Universe!

详情可查阅php手册:https://www.php.net/manual/zh/language.oop5.traits.php

0

评论 (0)

取消