'PHP Traits: define property and error "definition differs"
I have the following code and it works correctly:
abstract class ParentClass
{
public $flag = true;
}
class ChildClass extends ParentClass
{
public $flag = false;
}
var_dump((new ChildClass())->flag); // false
But if I use Trait it leads to Fatal Error
ParentClass and TFlag define the same property ($flag) in the composition of ChildClass. However, the definition differs and is considered incompatible. Class was composed in...`
abstract class ParentClass
{
public $flag = true;
}
trait TFlag
{
public $flag = false;
}
class ChildClass extends ParentClass
{
use TFlag;
}
var_dump((new ChildClass())->flag);
UPDATED:
It tested on PHP 7.1, 7.2, 7.4
Why is the following definition compatible for class inheritance and for logic, but not incompatible for trait?
- public $flag = true;
- public $flag = false;
UPDATED
I can override a method but not a property (it works):
abstract class ParentClass
{
public function flag(): bool
{
return true;
}
}
trait TFlag
{
public function flag(): bool
{
return false;
}
}
class ChildClass extends ParentClass
{
use TFlag;
}
var_dump((new ChildClass())->flag()); // false
Solution 1:[1]
The PHP Documentation is explicit about this (examples 12 and 13).
https://www.php.net/manual/en/language.oop5.traits.php#language.oop5.traits.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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | IGP |
