Base classes (usually abstract ones) can have methods which can be tuned with overriding constants in child classes. Those constants can also have default values.
example:
abstract class BaseClass{
const NAME = '<default name>';
public function sayHello(){
printf("Hello! My name is %s\n", static::NAME);
}
}
// will use default constant value
class SomeClass extends BaseClass{}
// constant value is overridden
class OtherClass extends BaseClass{
const NAME = 'Stephen Hawking';
}
(new SomeClass())->sayHello(); // Hello! My name is <default name>
(new OtherClass())->sayHello(); // Hello! My name is Stephen Hawking
But if I replace abstract class with trait I get
PHP Fatal error: Traits cannot have constants in /mnt/tmpfs/1.php on line 4
So is it possible to use them in traits?
Update:
This question header looks similar to this but they are completely different and somewhat opposite.
Other question is about defining constant in a trait and adding it to multiple classes. So the same constant value is added to different classes.
My question is about using constant in a method and overriding it in different classes. So different classes have different constant values which are used to configure a method.