[英]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.