How does insteadof keyword in a Trait work

流过昼夜 提交于 2019-12-12 07:53:47

问题


I was just reading about traits and how multiple php traits can be used in the same php code separated by commas. I do not however understand the concept of the insteadof keyword that is used to resolve conflict in case two traits have the same function. Can anyone please explain how insteadof keyword works and how to use it to tell the engine that I am willing to use function hello() of trait A instead of that of trait B, given there are two traits A and B and a function hello() in both the traits.


回答1:


Explanation

According to Traits Documentation, when you have same method in multiple trait, then you can explicitly guide the program to use method of specific trait by the use of insteadof operator. Refer to the example below which has been borrowed from above link, Here, when $t->smallTalk() is invoked it calls the smallTalk method in trait B insteadof trait A which is exactly the insteadof operator has been used for here. Since Class Talker uses trait A, B and both traits have smallTalk() method, we explicitly tell it to use trait B's smallTalk.

Example

<?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;
    }
}

$t = new Talker;
$t->smallTalk();
$t->bigTalk();

Output

bA

I hope this has cleared your confusion.



来源:https://stackoverflow.com/questions/39820753/how-does-insteadof-keyword-in-a-trait-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!