Blogger Information
Blog 24
fans 0
comment 0
visits 18497
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
trait命名冲突解决、trait中改变trait成员中的访问控制、trait与接口,抽象类联合编程
昔年
Original
815 people have browsed it

1、trait同名方法的命名冲突解决以及trait中改变trait成员的访问控制

<?php

trait tDemo1
{
    public function index()
    {
        echo __TRAIT__ . '=====>' . '首页';
    }
}


trait tDemo2
{
    public function index()
    {
        echo __TRAIT__ . '=====>' . '首页';
    }
}


trait tDemo3
{
    public function update()
    {
        echo __TRAIT__ . '====>' . '更新';
    }
}

trait tDemo4
{
    use tDemo1, tDemo2 {
        // 1. 替代
        tDemo1::index insteadof tDemo2;
        //2.重命名
        tDemo2::index as in2;
    }

    //修复访问权限
    use tDemo3 {
        update as protected up;
    }
}

class User
{
    use tDemo4;
}
//客户端
$user = new User;
$user->index();
echo '<br>';
$user->in2();
echo '<br>';
$user->up();
echo '<br>';

demo1.png

2.trait与抽象类、接口联合编程

<?php
interface iDemo
{
    public function sayHello();
    public function sayWord();
}


trait tDemo
{
    public function sayByebye()
    {
        echo 'ヾ(ToT)Bye~Bye~<br>';
    }
}

abstract class aDemo implements iDemo
{
    public function sayHello()
    {
        echo 'Hello<br>';
    }
}

class MyHelloWorld extends aDemo
{
    use tDemo;
    public function sayWord()
    {
        echo 'Word<br>';
    }
}

$my = new MyHelloWorld;
$my->sayByebye();
$my->sayHello();
$my->sayWord();

demo2.png


总结:trait同名冲突时有两种解决办法,一种是通过替代的方式来解决;另外一种是把其中一个方法的进行更名。

         使用trait时也可以进行相应的访问权限的变更。

        接口、抽象类、trait混合编程时,可以在接口中声明方法,然后抽象类中选择实现全部或者部分方法;trait则方便的实现了代码复用,一些常用的功能就可以放到trait中,需要使用时直接引入trait就行。



Correcting teacher:天蓬老师天蓬老师

Correction status:qualified

Teacher's comments:trait是你的好朋友
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!