繁体   English   中英

PHP 抽象 class 访问下面的常量

[英]PHP abstract class access of constant below

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

例如,我可以在 Generic 中分解 getName 吗?

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::之间的区别所在。更多信息可以在这里找到。

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;
    }
}

然后它将 output

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM