简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM