const的PHP接口继承


php interface inheritance of const

我想在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 ??如果没有声明颜色,会产生错误吗?我想有100%的信心,我可以使用这个Const,当我运行RandomFunction(trollTypeInterface $troll);

不能有抽象常量。最干净的解决方法是用getColor()等方法代替COLOR常数,使其抽象化。

你不能在PHP中这样做。您可以强制类实现方法,但不能设置变量或const。