PHP 抽象 class 下面常量的访问

PHP abstract class access of constant below

在PHP中是否有可能抽象class访问下面class的常量?

例如,我可以将 getName 分解为 Generic 吗?

abstract class Generic {
    abstract public function getName(): string;
}

class MorePreciseA extends Generic {
    private const NAME = "More Precise A";

    public function getName(): string {
        return self::NAME;
    }
}

class MorePreciseB extends Generic {
    private const NAME = "More Precise B";

    public function getName(): string {
        return self::NAME;
    }
}

谢谢

这就是 self::static:: 之间的区别所在。有关更多信息,请参见 here

abstract class Generic {
    protected const NAME = "Generic";

    public function getName(): string {
        return self::NAME;
    }
}

class MorePreciseA extends Generic {
    protected const NAME = "More Precise A";
}

class MorePreciseB extends Generic {
    protected const NAME = "More Precise B";

}


$a = new MorePreciseA();
$b = new MorePreciseB();

var_dump($a->getName(), $b->getName());

将导致

// string(7) "Generic"
// string(7) "Generic"

但是如果你像这样替换 Generic 实现

abstract class Generic {
    public function getName(): string {
        return static::NAME;
    }
}

然后会输出

// string(14) "More Precise A"
// string(14) "More Precise B"