[英]Accessing class constant from abstract method in PHP5
我试图获取扩展类的常量的值,但是在抽象类的方法中。 像这样:
abstract class Foo { public function method() { echo self::constant; } } class Bar extends Foo { const constant = "I am a constant"; } $bar = new Bar(); $bar->method();
然而,这会导致致命错误。 有没有办法做到这一点?
这不可能。 一种可能的解决方案是创建一个虚拟方法,该方法返回子类中的所需值,即
abstract class Foo {
protected abstract function getBar();
public function method() {
return $this->getBar();
}
}
class Bar extends Foo {
protected function getBar() {
return "bar";
}
}
本质上, self
指的是编写代码的当前类,而static
指的是运行代码的类。
我们可以将您的代码片段重写为:
abstract class Foo {
public function method() {
echo static::constant; // Note the static keyword here
}
}
class Bar extends Foo {
const constant = "I am a constant";
}
$bar = new Bar();
$bar->method();
但是,这种编码模式很脏,您可能应该在父类和子类之间引入受保护的 api 来来回汇集此类信息。
所以从代码组织的角度来看,我更倾向于Morfildur提出的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.