How does insteadof keyword in a Trait work

匆匆过客 提交于 2019-12-03 15:50:55

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.

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