从 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();
但这会导致致命错误。有什么办法可以做到这一点吗?
I'm trying to get the value of a constant of an extending class, but in a method of the abstract class. Like this:
abstract class Foo { public function method() { echo self::constant; } } class Bar extends Foo { const constant = "I am a constant"; } $bar = new Bar(); $bar->method();
This however results in a fatal error. Is there any way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可以使用 PHP 5.3 中引入的 Late Static Binding 关键字实现。
本质上,
self
指的是编写代码的当前类,但static
指的是代码所在的类正在运行。我们可以将您的代码片段重写为:
但是,这种编码模式很脏,您可能应该在父类和子类之间引入受保护的 api 来来回传输此类信息。
所以从代码组织的角度来看,我更倾向于Morfildur提出的解决方案。
This is possible using the Late Static Binding keyword introduced in PHP 5.3
Essentially,
self
refers to the current class that the code is written in, butstatic
refers to the class the code is running from.We could rewrite your code snippet as:
However, this pattern of coding is dirty and you should probably instead introduce a protected api between your parent class and subclasses to funnel that kind of information back and forth.
So from a code organization perspective, I would lean more towards the solution that Morfildur put forward.
这是不可能的。一种可能的解决方案是创建一个虚拟方法,该方法返回子类中所需的值,即
This is not possible. A possible solution would be to create a virtual method that returns the desired value in the subclasses, i.e.