Blogger Information
Blog 22
fans 1
comment 1
visits 22662
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
php中trait
forever浅笑
Original
721 people have browsed it

实例

<?php

class animal
{
    private $name = "动物";

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

    public function speak()
    {
        echo $this->name . '正在说话...';
    }
}

trait first_trait
{
    private $name = '小狗';

    public function speak()
    {
        echo $this->name . '正在汪汪叫...';
    }
}

class Dog extends animal
{
    public function __construct($name)
    {
        parent::__construct($name);
    }

    use first_trait;


}

$dog = new Dog('小狗');
$dog->speak();

运行实例 »

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

总结:

    1. trait类似于一个方法集,不能被实例化

    2. 同名方法的优先级:子类>Trait类>父类

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!