Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final abstract class in PHP?

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:

  • not be allowed to be extended
  • not be allowed to be instantiated

Why does the Interpreter dissallow this and how shall I implement it?

like image 726
Blackbam Avatar asked Nov 07 '18 16:11

Blackbam


1 Answers

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.

like image 171
Matteo Tassinari Avatar answered Oct 24 '22 22:10

Matteo Tassinari