Overriding Doctrine Trait Properties

僤鯓⒐⒋嵵緔 提交于 2019-11-30 08:12:05

You cannot override a trait's property in the class where the trait is used. However, you can override a trait's property in a class that extends the class where the trait is used. For example:

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

abstract class ParentClass
{
    use ExampleTrait;
}

class ChildClass extends ParentClass
{
    protected $someProperty = 'bar';
}

My solution was to use the constructor, example:

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

class MyClass
{
    use ExampleTrait;

    public function __construct()
    {
         $this->someProperty = 'OtherValue';
    }
}

An alternative solution, in this case using the property updatable.

I use this when the property is only required within the trait's methods...

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

...and using the trait in a class.

class MyClass
{
    use MyTrait;

    /**
     * If you need to override the default value, define it here...
     */
    protected $my_trait_updatable = 'overridden';
}

You can declare a trait property in a class but you must keep the same definition from the trait. It couldn't be overridden with different definition. So, as you already has access to trait properties from class, it's not needed to redefined again. Think that a trait works as a copy paste code.

<?php
trait FooTrait 
{
    protected $same       = '123';
    protected $mismatch  = 'trait';
}

class FooClass 
{
    protected $same      = '123';

    // This override property produces: 
    // PHP Fatal error:  FooClass and FooTrait define the same property
    // ($mismatchValue) in the composition of FooClass. However, the definition
    // differs and is considered incompatible
    protected $mismatch  = 'class';

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