有没有办法在静态方法中检测目标类?

Ada*_*nco 1 php oop php-5.2 php-5.3

下面是一个示例类层次结构和代码.我正在寻找一种方法来确定'ChildClass1'或'ChildClass2'是否具有静态方法whoAmI()在其上调用它而不在每个子类中重新实现它.

<?php

abstract class ParentClass {

    public static function whoAmI () {

        // NOT correct, always gives 'ParentClass'
        $class = __CLASS__;

        // NOT correct, always gives 'ParentClass'. 
        // Also very round-about and likely slow.
        $trace = debug_backtrace();
        $class = $trace[0]['class'];

        return $class;
    }
}

class ChildClass1 extends ParentClass {

}

class ChildClass2 extends ParentClass {

}

// Shows 'ParentClass'
// Want to show 'ChildClass1'
print ChildClass1::whoAmI(); 
print "\n";

// Shows 'ParentClass'
// Want to show 'ChildClass2'
print ChildClass2::whoAmI();
print "\n";
Run Code Online (Sandbox Code Playgroud)

Ken*_*ric 7

我相信你所指的是一个已知的php bug.Php 5.3旨在通过新的Late Static Binding功能来解决这个问题.

http://www.colder.ch/news/08-24-2007/28/late-static-bindings-expl.html