PHP get_called_class() alternative PHP get_called_class() alternative php php

PHP get_called_class() alternative


In reality it is often helpful to know the actual called (sub)class when executing a superclass method, and I disagree that there's anything wrong with wanting to solve this problem.

Example, my objects need to know the class name, but what they do with that information is always the same and could be extracted into a superclass method IF I was able to get the called class name. Even the PHP team thought this was useful enough to include in php 5.3.

The correct and un-preachy answer, as far as I can tell, is that prior to 5.3, you have to either do something heinous (e.g. backtrace,) or just include duplicate code in each of the subclasses.


Working solution:

function getCalledClass(){    $arr = array();     $arrTraces = debug_backtrace();    foreach ($arrTraces as $arrTrace){       if(!array_key_exists("class", $arrTrace)) continue;       if(count($arr)==0) $arr[] = $arrTrace['class'];       else if(get_parent_class($arrTrace['class'])==end($arr)) $arr[] = $arrTrace['class'];    }    return end($arr);}


This is not possible.

The concept of "called class" was introduced in PHP 5.3. This information was not tracked in previous versions.

As an ugly work-around, you could possibly use debug_backtrace to look into the call stack, but it's not equivalent. For instance, in PHP 5.3, using ClassName::method() doesn't forward the static call; you have no way to tell this with debug_backtrace. Also, debug_backtrace is relatively slow.