Skip to content

Instantly share code, notes, and snippets.

@kylefarris
Forked from hamstar/php-calling-class-test.php
Last active March 1, 2022 14:24
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kylefarris/5188645 to your computer and use it in GitHub Desktop.
Save kylefarris/5188645 to your computer and use it in GitHub Desktop.
/***********************************************************
******* SIMPLE TEST **/
class A {
function t() {
echo get_calling_class();
}
}
class B {
function x() {
$a = new A;
$a->t();
}
}
$b = new B;
$b->x(); // prints B
<?php
function get_calling_class() {
//get the trace
$trace = debug_backtrace();
// Get the class that is asking for who awoke it
$class = ( isset( $trace[1]['class'] ) ? $trace[1]['class'] : NULL );
// +1 to i cos we have to account for calling this function
for ( $i=1; $i<count( $trace ); $i++ ) {
if ( isset( $trace[$i] ) && isset( $trace[$i]['class'] ) ) // is it set?
if ( $class != $trace[$i]['class'] ) // is it a different class
return $trace[$i]['class'];
}
}
@kylefarris
Copy link
Author

Should be checking that the 'class' index exists, as well, before using it.

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