Overriding Doctrine Trait Properties

DanHabib picture DanHabib · Sep 14, 2015 · Viewed 17.1k times · Source

I know you can override a trait method by declaring it in your class, I was curious if was possible to over ride a trait Property the same way. Is this safe to do? Its not in the Documentation so I am hesitant to implement this.

From the Documentation

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

Answer

Mathew Tinsley picture Mathew Tinsley · Jul 25, 2016

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';
}