4

有什么方法可以在 PHP 中确定父类中的子实例?假设我们有以下代码:

class Parent {
    public function InstanceOfChild() {
        //What to put here to display "Child class is instance of ChildClass123"?
    }
}

class ChildClass123 extends Parent {
   //Some code here
}

我需要做的(如果可能的话)是创建方法InstanceOfChild(),它会告诉我子类的实例,因为很多类都可以是我父类的子类,但我想(比如说)记录,哪个子类调用哪些方法. 感谢帮助!

4

3 回答 3

8

有一个get_called_class()您正在寻找的功能。

class Parent1 {
    public static function whoAmI() {
        return get_called_class();
    }
}

class Child1 extends Parent1 {}

print Child1::whoAmI(); // prints "Child1"
于 2013-08-15T06:58:53.517 回答
2
class Parent {
    public function InstanceOfChild() {
        $class = get_class($this);
        return $class == 'Parent'? // check if base class
           "This class is not a child": // yes
           "Child class is instance of " . $class; // its child
    }
}

请注意,调用:

$this instanceof Parent

将始终返回 true,因为 parent 和 children 都是 Parent 类的实例。

于 2013-08-15T06:57:09.050 回答
0

您可以使用get_class. 因此,您必须设置以下代码:

echo "Child class is instance of ".get_class($childInstance);

(我不是 php 开发人员,所以语法可能有误)

于 2013-08-15T06:55:34.347 回答