覆盖Doctrine Trait属性

Dan*_*bib 21 php traits

我知道你可以通过在你的课堂上声明它来覆盖一个trait 方法,我很好奇是否有可能以同样的方式过度使用一个trait 属性.这样做安全吗?它不在文档中,所以我对实现这一点犹豫不决.

来自文档

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in turn override inherited methods.

http://php.net/manual/en/language.oop5.traits.php

Mat*_*ley 38

您不能在使用特征的类中覆盖特征的属性.但是,您可以在扩展使用特征的类的类中覆盖特征的属性.例如:

trait ExampleTrait
{
    protected $someProperty = 'foo';
}

abstract class ParentClass
{
    use ExampleTrait;
}

class ChildClass extends ParentClass
{
    protected $someProperty = 'bar';
}
Run Code Online (Sandbox Code Playgroud)

  • 我很好奇,这背后的逻辑是什么?*儿子不会因父亲的罪孽受到惩罚.* (10认同)
  • 如果有人仍然想知道的话,原因是特征只是简单的复制粘贴。您不能在一个类中两次定义相同的属性,但您可以在子类中重写它 - 每当您想知道特征的陌生性时,请考虑一下如果您只是将“use Trait”替换为代码,代码将如何工作逐字逐句地看,这一切又变得有意义了。真的没什么别的了。 (9认同)
  • 有时我认为 PHP 的创建者在捉弄我。 (4认同)
  • @MoritzFriedrich 这应该是有意义的,但事实并非如此。“_traits 只是复制粘贴_” - 正确,但它们允许将_方法_粘贴到类的具体方法上_并且_提供一种在需要时解决冲突的机制。为什么财产不应该有同样的特权?从之前的评论来看,我倾向于倾向于巨魔理论。 (3认同)

ped*_*dev 12

我的解决方案是使用构造函数,例如:

trait ExampleTrait
{
    protected $someProperty = 'foo';
}

class MyClass
{
    use ExampleTrait;

    public function __construct()
    {
         $this->someProperty = 'OtherValue';
    }
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*eve 8

另一种解决方案,在本例中使用属性updatable.

当仅在特征的方法中需要该属性时,我使用它......

trait MyTrait
{
    public function getUpdatableProperty()
    {
        return isset($this->my_trait_updatable) ?
            $this->my_trait_updatable:
            'default';
    }
}
Run Code Online (Sandbox Code Playgroud)

...并在课堂上使用该特征。

class MyClass
{
    use MyTrait;

    /**
     * If you need to override the default value, define it here...
     */
    protected $my_trait_updatable = 'overridden';
}
Run Code Online (Sandbox Code Playgroud)