如何从php中的父类获取子类名

时间:2012-11-03 05:07:29

标签: php inheritance

<?php

class parentClass {

    function myChild() {
        echo 'Child Class Name: '.__CLASS__;
    }   
}

class childClass extends parentClass {

}

$childClassObj = new childClass;

$childClassObj->myChild();

输出

Child Class Name: parentClass

实际上,我期待输出

Child Class Name: childClass

我该怎么做才能获得输出?

2 个答案:

答案 0 :(得分:7)

您可以使用get_called_class

<?php
    class parentClass {

        function myChild() {
           echo 'Child Class Name: '.get_called_class();
        }   
    }

    class childClass extends parentClass {

    }

    $childClassObj = new childClass;

    $childClassObj->myChild(); //childClass
?>

答案 1 :(得分:2)

你试过这个:

function myChild() {
   echo 'Child Class Name: '.get_class($this);
}