【问题标题】:PHP Trait using another trait, calling a method from the used traitPHP Trait 使用另一个 trait,从使用的 trait 调用方法
【发布时间】:2020-04-15 17:15:35
【问题描述】:

我有一个 MyTranslatable 特征,它使用另一个 OtherTranslatable 特征,即来自第三方包的特征。我将它们包括在内。

trait MyTranslatable
{
    use OtherTranslatable {
        OtherTranslatable::method as public otherTranslatableMethod;
    }

    public function index()
    {
        // Perform my actions

        // Call otherTranslatableMethod
        static::otherTranslatableMethod();
    }

我想知道这是否有效,代码是否正常工作,但我不太确定是否要以这种方式使用特征,以及这是否是调用“父特征”方法的正确方法我的动作完成后

【问题讨论】:

  • 当然,这是有效的。
  • 它可能是有效的,是否合适是有争议的,但没有足够的上下文来说明。但可能不是,特质很少适合。 trait 意味着多重继承,多重继承意味着违反 SRP...

标签: php traits


【解决方案1】:

我认为从架构的角度来看您的代码是正确的,因为 PHP 中的子蓝图(类、特征)可以在上下文的 use 语句中覆盖,来自已使用特征的方法(我避免调用此继承,因为使用特征实际上是复制粘贴),但我觉得在MyTranslatable 中静态调用你的otherTranslatableMethod() 并不是很必要(当然,除非它在OtherTranslatable 特征中定义为静态)。

如果您有OtherTranslatable->method() 的非静态定义,您可以执行以下操作以使您的代码更加正确和干净。

trait MyTranslatable
{
    use OtherTranslatable {
        method as public otherTranslatableMethod;
    }

    public function index()
    {
        // Perform my actions
        // Call otherTranslatableMethod
        $this->otherTranslatableMethod();
    }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多