php - 在 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() 并在运行时抛出异常。
请帮助我编写这个不变量。我尝试了很多东西,但不知何故它不能正常工作。
解决方案
您可以使用方法定义一个类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
.
推荐阅读
- pandas - 熊猫 date_time 有什么问题?
- graphql - 如何在graphene-django中使用节流?
- amazon-web-services - 我可以向 S3 发送 CloudWatch Metrics 命名空间吗?
- ruby-on-rails - 为什么在部署到新的 Heroku 服务器时出现 nokogiri 和 mini_portile2 依赖错误?
- visual-studio-code - 如何使用“Visual Studio Code Remote - SSH”设置与 Vagrant 容器的远程连接?
- r - 将函数应用于具有数字对象的数据框并打印小数点/尾随零
- c# - 在 Smartsheet 更新/插入之前设计在 c# 或 SQL 或两者中对数据进行排序的最佳实践
- ios - PageView 中子视图之间的条件更改
- c# - 如何使用 Unity3D 中的脚本让两个游戏对象面对面
- botframework - 如何在机器人首次启动时实施欢迎活动 - NLP 来自 Google Dialogflow