我想在PHP中做这样的事情:
interface trollTypeInterface
{
// ????
public function scareNaughtyKids()
}
interface trollFrozenInterface extends trollTypeInterface
{
const COLOR = "lightblue and white"
public function changeSnowColorToYellow();
}
interface trollForestInterface extends trollTypeInterface
{
const COLOR = "bronze and green"
public function cleanUpHollowInTheTree();
}
interface trollUfoInterface extends trollTypeInterface
{
//forgotten const COLOR should cause error
}
如何判断,从父trollTypeInterface
出生的所有接口都必须有const COLOR
?如果没有声明颜色会产生错误?当我运行RandomFunction(trollTypeInterface $ troll)时,我希望100%有信心可以使用这个Const;
答案 0 :(得分:2)
你不能有抽象常数。最干净的解决方案是用COLOR
之类的方法替换getColor()
常量,并使其成为抽象的。
答案 1 :(得分:1)
您无法在PHP中执行此操作。您可以强制类实现方法,但不能设置变量或const。