php – 避免特质碰撞 – use_once?

栏目: PHP · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/36269607/avoiding-trait-collisions-use-once
我有两个 PHP

特征,每个特征都继承自相同的第三特征:

trait C {
    public function smallTalk() {
        echo 'c';
    }
}

trait A {
    use C;
    public function ac() {
        echo 'a'.smallTalk();
    }
}

trait B {
    use C;
    public function bc() {
        echo 'b'.smallTalk();
    }
}

我想在课堂上使用它们:

class D {
    use A, B;
    public function acbc() {
        echo ac().bc();
    }
}

但我一直在收到错误

Fatal error: Trait method smallTalk has not been applied, because there are collisions with other trait methods on D

我知道use_once不是一个东西,但我正在寻找require_once或include_once提供的相同功能,但是对于特征.这个例子很简单.我的真正的C有很多方法,并且被超过2个特征继承,所以我不想在每次使用超过1个这些特征时重复一长串的代替.

您需要阅读: Conflict Resolution

If two Traits insert a method with the same name, a fatal error is

produced, if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class, the

insteadofoperator needs to be used to choose exactly one of the

conflicting methods.

Since this only allows one to exclude methods, the as operator can be

used to allow the inclusion of one of the conflicting methods under

another name.

例:

<?php
trait A {
    public function smallTalk() {
        echo 'a';
    }
    public function bigTalk() {
        echo 'A';
    }
}

trait B {
    public function smallTalk() {
        echo 'b';
    }
    public function bigTalk() {
        echo 'B';
    }
}

class Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
    }
}

class Aliased_Talker {
    use A, B {
        B::smallTalk insteadof A;
        A::bigTalk insteadof B;
        B::bigTalk as talk;
    }
}

翻译自:https://stackoverflow.com/questions/36269607/avoiding-trait-collisions-use-once


以上所述就是小编给大家介绍的《php – 避免特质碰撞 – use_once?》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

响应式Web设计

响应式Web设计

本·弗莱恩 (Ben Frain) / 奇舞团 / 人民邮电出版社 / 2017-2-1 / CNY 59.00

本书将当前Web 设计中热门的响应式设计技术与HTML5 和CSS3 结合起来,为读者全面深入地讲解了针对各种屏幕大小设计和开发现代网站的各种技术。书中不仅讨论了媒体查询、弹性布局、响应式图片,更将最新和最有用的HTML5 和CSS3 技术一并讲解,是学习最新Web 设计技术不可多得的佳作。一起来看看 《响应式Web设计》 这本书的介绍吧!

MD5 加密
MD5 加密

MD5 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试