Reputation: 1217
The PHP docs says the following about overriding trait properties:
If a trait defines a property then a class can not define a property with the same name unless it is compatible (same visibility and initial value), otherwise a fatal error is issued.
However, when you use a trait in an abstract class, then you can override the properties defined in the trait in a class extending that abstract class:
<?php
trait PropertyTrait
{
public $prop = 'default';
}
abstract class A
{
use PropertyTrait;
}
class B extends A
{
public $prop = 'overridden';
public function write()
{
echo $this->prop;
}
}
$b = new B();
$b->write(); // outputs "overridden"
The code above works, but I can't find any reference about it in the documentation. Is this an intended feature?
Upvotes: 1
Views: 610
Reputation: 47359
Because for all intents and purposes B
is not using PropertyTrait
. That's used by A
to compose the abstract class.
B
has no visibility of what traits A
is using. If you were to execute class_uses
on B
, you'd get an empty array. Docs, and example.
Since B
is not using any traits, the class is free to override any inherited properties.
The fact that A
is an abstract class has no bearing on this. The same behaviour would happen with any class that extended a class that was composed using traits.
Upvotes: 3