精易论坛

标题: PHP - trait命名冲突解决办法与实战小案例 [打印本页]

作者: dream518    时间: 2020-7-19 11:03
标题: PHP - trait命名冲突解决办法与实战小案例
[md]## 1. trait 命名冲突解决办法
```php
<?php
//trait组合中的方法命名冲突解决办法

trait tDemo1
{
    public static function abc()
    {
        return '名字:123';
    }
}

trait tDemo2
{
    public static function abc()
    {
        return '年龄:18';
    }
}

trait tDemo3
{
    use tDemo1,tDemo2{
//        先替代 然后给别名
        tDemo2::abc insteadof tDemo1;
        tDemo1::abc as ab;
    }


}

class Aname
{
    use tDemo3;
}
$aname = new Aname();

echo $aname->ab();

```

## 2. trait  与 interface 接口进行组合
```php
<?php
//trait  与 interface 接口进行组合

//创建接口
//判断一下 如果当前没有这个接口 那么创建
if (!interface_exists('iDemo')){
    interface iDemo {
//        创建一个静态抽象方法
    public static function index();
    }
}

//创建trait
//也判断一下
if (!trait_exists('tDemo')){
    trait tDemo{
//        实现接口中的index方法
    public  static  function index(){
        return __CLASS__.'类嗲用了'.__METHOD__.'方法';
    }
    }
}

//创建工作类
//也判断一下
if (!class_exists('Cla')){
    class Cla implements iDemo
    {
        use tDemo;
    }
}

//访问
echo Cla::index();
//输出   Cla类嗲用了tDemo::index方法
```


## 3. 一个简单的抽奖

```php
<?php

//设置奖品
$prizes = ['电脑', '手机', '平板', '耳机', '拖鞋', '口罩'];

//创建接口生成唯一ID抽象类
interface onlyId
{
//生成唯一id
    public static function getOnlyId(int $min, int $max):int;
}

//创建trait实现抽象类
trait AbalonesId
{
//    实现唯一id  传两个参数 最大值 最小值
    public static function getOnlyId(int $min, int $max): int
    {
        return mt_rand($min, $max);
    }

//    返回奖品
    public static function prize($prizes, $id)
    {

        return $prizes[$id];
    }
}

//创建工作类

class DrawPrize implements onlyId
{
    use AbalonesId;
}
$id = DrawPrize::getOnlyId(0, 5);
echo DrawPrize::prize($prizes,$id);
//随机输出数组prizes中的值

```







欢迎光临 精易论坛 (https://125.confly.eu.org/) Powered by Discuz! X3.4