简体   繁体   中英

PHP: Get name of the class the current function was defined in

In PHP I'd like to find out in a function in which class this function was defined in, even if it was inherited by another class.

Let me give you an example:

class cParent {
   function getDefinedInClassName() {
      return function_I_am_looking_for();
   }
}

class cChild1 extends cParent {
}

class cChild2 extends cParent {
   function getDefinedInClassName() {
      return parent::getDefinedInClassName();
   }
}

$objParent = new cParent();
$objParent->getDefinedInClassName(); // should return 'cParent'

$objChild1 = new cChild1();
$objChild1->getDefinedInClassName(); // should return 'cParent'

$objChild2 = new cChild2();
$objChild2->getDefinedInClassName(); // should return 'cChild2'

EDIT :

Just realized I had an error in the code. I have corrected it. Now it shows the actual problem. Sorry for the mistake!

http://php.net/manual/function.get-class.php I think you should try this function.

get_class($this) 

will return the name of the current class.

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