php – 避免特质碰撞 – use_once?

前端之家收集整理的这篇文章主要介绍了php – 避免特质碰撞 – 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
insteadof operator 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://www.f2er.com/php/136065.html

猜你在找的PHP相关文章