Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding Doctrine Trait Properties

Tags:

php

traits

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

like image 296
DanHabib Avatar asked Sep 14 '15 18:09

DanHabib


People also ask

How do you override a trait in laravel?

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".

Can traits have properties PHP?

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.

What is a trait PHP?

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.


2 Answers

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'; } 
like image 100
Mathew Tinsley Avatar answered Sep 20 '22 23:09

Mathew Tinsley


My solution was to use the constructor, example:

trait ExampleTrait {     protected $someProperty = 'foo'; }  class MyClass {     use ExampleTrait;      public function __construct()     {          $this->someProperty = 'OtherValue';     } } 
like image 28
pedro.caicedo.dev Avatar answered Sep 22 '22 23:09

pedro.caicedo.dev