php:在静态方法中获取继承类的名称
好吧,帖子标题可能有点令人困惑。
我有这样的代码:
class A {
public static foo() {
return get_called_class();
}
}
class B extends A {
}
class C {
public function bar() {
echo B::foo();
}
}
输出:C
我想在 foo() 中获取的是 B 的类名。在不更改 B 类的情况下如何才能做到这一点?
问候, Jan Oliver
PS:__ CLASS __,get_class() 不起作用。
Okay, the post title might be a little confusing.
I have this code:
class A {
public static foo() {
return get_called_class();
}
}
class B extends A {
}
class C {
public function bar() {
echo B::foo();
}
}
Output: C
WHat I want to get in foo() is the class name of B. How can I do this without changes in the class B?
Regards,
Jan Oliver
PS: __ CLASS __, get_class() are not working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 PHP 5.3 之前,如果没有 hack,这是不可能实现的,这被称为后期静态绑定,这是一个可在 google 上搜索到的术语。
如果您有兴趣,这里是带有答案的 SO 文章:假装迟到php 5.3之前的静态绑定
Before PHP 5.3, this is not possible without hacks and is known as late static binding, a googleable term.
If you're interested, here is the SO article with answers: Faking Late Static Binding before php 5.3
我认为你可以使用内置的 反射类 为此。
I think you could use the built-in Reflection class for that.