首页 > 解决方案 > 在 Hack PHP 中限制函数覆盖的不变式

问题描述

我在 PHP Hack 中有一个带有函数的基类:

// This method is used to return just one Apple Type
protected static function Apple(): AppleType {
    return AppleType;
}

现在我有两种类型的类——一种使用基本特征,一种不使用。

该特征具有以下功能:

// This method is used to return more than one Apple Type
protected static function Apples(): keyset[AppleType] {
    return keyset[AppleType];
}

不使用此特征的子类可以覆盖基类 Apple() 方法。但是确实使用 trait 的类必须重写 Apples() 而不是 Apple()。

现在我想提供一个不变的异常:

就像是:

invariant(Apple() is not overridden in this class, 'Class must override Apples() and not Apple()');

即不变量提供强制使用 trait 的类不能覆盖基类的 Apple() 并在运行时抛出异常。

请帮助我编写这个不变量。我尝试了很多东西,但不知何故它不能正常工作。

标签: phpinvariantshacklang

解决方案


您可以使用方法定义一个类final,并要求 trait 用户扩展该类。

enum AppleType: int {
  Fresh = 1;
  Stale = 2;
}

class Overridable {
  protected static function Apple(): AppleType {
    return AppleType::Fresh;
  }
}

class MustUseApples extends Overridable {
  <<__Override>>
  final protected static function Apple(): AppleType {
    return parent::Apple();
  }
}

trait MyTrait {
  require extends MustUseApples;

  protected static function Apples(): keyset<AppleType> {
    return keyset[AppleType::Stale];
  }
}

但是,如果您想要求 trait 用户必须提供 的实现Apples,您可能应该将其设为MustUseApples.


推荐阅读