【问题标题】:php: get the name of an inheriting class in a static methodphp:在静态方法中获取继承类的名称
【发布时间】:2010-02-20 13:47:36
【问题描述】:

好的,帖子标题可能有点混乱。

我有这个代码:

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 类的情况下做到这一点?

问候, 简·奥利弗

PS:__ CLASS __,get_class() 不起作用。

【问题讨论】:

标签: php static-methods late-binding


【解决方案1】:

在 PHP 5.3 之前,如果没有 hack,这是不可能的,这被称为后期静态绑定,这是一个 googleable 术语。

如果您有兴趣,这里是带有答案的 SO 文章:Faking Late Static Binding before php 5.3

【讨论】:

  • 我阅读了 php 的文档,但我没有找到解决问题的方法,因为我不想更改 B 类。
  • 正如我所提到的,如果你使用低于 5.3 的 php,没有我提供的 hack 是不可能的:stackoverflow.com/questions/890505/…
【解决方案2】:

我认为您可以为此使用内置的 Reflection class

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-06
    • 2011-05-15
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多