Trait 中的替代关键字如何工作 [英] How does insteadof keyword in a Trait work

查看:19
本文介绍了Trait 中的替代关键字如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚阅读了有关traits 以及如何在以逗号分隔的同一php 代码中使用多个php trait 的内容.然而,我不明白在两个特征具有相同功能的情况下用于解决冲突的替代关键字的概念.任何人都可以解释而不是关键字如何工作以及如何使用它来告诉引擎我愿意使用特征 A 的函数 hello() 而不是特征 B 的函数,因为有两个特征 A 和 B 以及一个函数 hello() 在这两个特征中.

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.

推荐答案

说明

根据 Traits 文档,当您在多个相同的方法trait,那么你可以通过使用insteadof操作符来明确引导程序使用特定trait的方法.参考下面的例子,这个例子是从上面的链接借来的,这里,当 $t->smallTalk() 被调用时,它会调用 trait B 中的 smallTalk 方法而不是 trait A 正是这里使用的替代运算符.由于 Class Talker 使用 trait A、B 并且两个 trait 都有 smallTalk() 方法,我们明确告诉它使用 trait B 的 smallTalk.

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.

<?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();

输出

bA

我希望这能消除您的困惑.

I hope this has cleared your confusion.

这篇关于Trait 中的替代关键字如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆