[英]PHP abstract class access of constant below
Is it possible in PHP, that an abstract class accesses a constant of the class below?在 PHP 中,抽象 class 是否可以访问下面的 class 的常量?
For example, can I factorize getName in Generic?例如,我可以在 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;
}
}
Thanks谢谢
This is where the difference between self::
and static::
comes in. More on that can be found here .这就是
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());
Will result in会导致
// string(7) "Generic"
// string(7) "Generic"
But if you replace the Generic
implementation like so但是如果你像这样替换
Generic
实现
abstract class Generic {
public function getName(): string {
return static::NAME;
}
}
Then it will output然后它将 output
// string(14) "More Precise A"
// string(14) "More Precise B"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.