PHP 中的最终摘要 class?

Final abstract class in PHP?

我想达到的目标:

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();
    }
}

解释器不允许这样做:

Fatal error: Cannot use the final modifier on an abstract class in ...

但是我想将其用作“常量永不修改的枚举”。它应该:

为什么 Interpreter 不允许这样做,我该如何实施?

您可以将其设为 final 并为其提供私有构造函数:

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() {}
}

在这里,"final" 负责 "cannot be extended" 要求,而私有构造函数负责 "cannot be instantiated"。

至于"why"你做不到,因为这是语言规范;另外,正如@CD001 在他的评论中指出的那样:

The whole point of abstract classes is that they are to be extended so abstract final is sort of a contradiction

实际上有一个 RFC 可以改变它,但它似乎没有成功。