在父类中获取子实例

时间:2013-08-15 06:50:28

标签: php oop parent-child

有没有办法如何在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(),它将告诉我子类的实例,因为很多类可以是我父类的子类,但我想(让我们说) )log,哪个子调用哪些方法。谢谢你的帮助!

3 个答案:

答案 0 :(得分:8)

您正在寻找的功能 get_called_class()

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

class Child1 extends Parent1 {}

print Child1::whoAmI(); // prints "Child1"

答案 1 :(得分: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类的实例。

答案 2 :(得分:0)

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

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

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

相关问题