php:在静态方法中获取继承类的名称

发布于 2024-08-22 11:09:51 字数 370 浏览 14 评论 0原文

好吧,帖子标题可能有点令人困惑。

我有这样的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

初雪 2024-08-29 11:09:51

在 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

萌酱 2024-08-29 11:09:51

我认为你可以使用内置的 反射类 为此。

I think you could use the built-in Reflection class for that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文