简体   繁体   中英

How to get child class name from parent class in php

<?php

class parentClass {

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

class childClass extends parentClass {

}

$childClassObj = new childClass;

$childClassObj->myChild();

The output is

Child Class Name: parentClass

Actually, I am expecting an output

Child Class Name: childClass

What should I do to get the output?

You can use 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
?>

Have you tried this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM