Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A function that will return the calling class to the class using it
******* SIMPLE TEST **/
class A {
function t() {
echo get_calling_class();
class B {
function x() {
$a = new A;
$b = new B;
$b->x(); // prints B
function get_calling_class() {
//get the trace
$trace = debug_backtrace();
// Get the class that is asking for who awoke it
$class = $trace[1]['class'];
// +1 to i cos we have to account for calling this function
for ( $i=1; $i<count( $trace ); $i++ ) {
if ( isset( $trace[$i] ) ) // is it set?
if ( $class != $trace[$i]['class'] ) // is it a different class
return $trace[$i]['class'];

This comment has been minimized.

Copy link

@kylefarris kylefarris commented Mar 18, 2013

Hey, I forked and made a change to check to make sure the 'class' index exists since I ran into that problem in my testing. I'd suggest modifying your gist to account for the change. Unfortunately, I can't do a pull request on a gist, but, you can check out my fork to see the diff:

Thanks for sharing!


This comment has been minimized.

Copy link

@grobertson grobertson commented Mar 30, 2013

This is exactly what I needed at this moment. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment