What I want to achieve:
abstract final class NoticeTypes {
const ERROR = "error";
const WARNING = "warning";
const INFO = "info";
const SUCCESS = "success";
static function getAll() {
$oClass = new ReflectionClass(__CLASS__);
return $oClass->getConstants();
}
}
The interpreter does not allow this:
Fatal error: Cannot use the final modifier on an abstract class in ...
However I want to use this as kind of a "constant never-modifiable enum". It should:
Why does the Interpreter dissallow this and how shall I implement it?
You could make it final and give it a private constructor:
final class NoticeTypes {
const ERROR = "error";
const WARNING = "warning";
const INFO = "info";
const SUCCESS = "success";
static function getAll() {
$oClass = new ReflectionClass(__CLASS__);
return $oClass->getConstants();
}
private function __construct() {}
}
Here, "final" takes care for the "cannot be extended" requirement, while the private constructor takes care of "cannot be instantiated".
As for the "why" you cannot do it, it is just because such is the language specification; also, as @CD001 points out in his comment:
The whole point of abstract classes is that they are to be extended so abstract final is sort of a contradiction
There was actually an RFC to change that, but it seems it didn't make it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With