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