Blogger Information
Blog 42
fans 3
comment 2
visits 40510
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait的运用
虞者自愚的博客
Original
757 people have browsed it

实例

<meta charset=utf-8>
<?php

//先创建一个父类
if(!class_exists('shejibu')) {
    class shejibu
    {
        protected $name;
        public function __construct($name='小刘')
        {
            $this->name=$name;
        }
        public function work($sheji='实木家具设计')
        {
            return $this->name.'的工作是'.$sheji;
        }

    }
}
//第一个trait
if(!trait_exists('Laoda')){
    trait Laoda
    {
        public $boss='设计部主管';
        public function test($shijian='今天下班前')
        {
            return $this->boss.'让'.$this->name.$shijian.'把设计图给他';
        }
    }

}
//再写一个trait
if(!trait_exists('Boss'))
{
    trait Boss
    {
        public $leader='老大';
        public function test($num='1000'){
            return $this->leader.'觉得'.$this->name.'工作完成的很棒,给'.$this->name.'奖励了'.$num.'元奖金';
        }

    }
}
//子类
if(!class_exists('programmer'))
{
    class programmer extends shejibu
    {     //子类支持导入多个trait类,方法重名的话用下列方法解决

        use Laoda,Boss{
            //重名的test 用Mission::test代替掉Boss::test
            Laoda::test insteadof Boss;
            //在用holiday代替Boss::test
            Boss::test as jiangjin;


        }
    }
}
//实例化子类
$programmer=new programmer();
//调用父类中的方法
echo $programmer->work();
echo'<hr>';
//访问trait类中的方法
echo $programmer->test();
echo'<hr>';
//调用trait中重名的方法
echo $programmer->jiangjin();

运行实例 »

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

00.png

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