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
Overriding a trait function Let's create a simple trait and use it in a class. Executing (new MyClass)->sayHi(); will output "trait says hi". The trait function can be overridden simply by defining a function with the same name in the class. Now (new MyClass)->sayHi(); will output "class says hi".
Traits can have properties and methods with private and protected visibility too. You can access them like they belong to class itself. There is no difference.
Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.
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'; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With