ao-pack
ao-pack

Reputation: 27

Alternative way of getting the called class in PHP

Is there an alternative way other than debug_backtrace() to know the name of the class that is calling my script?

Upvotes: 0

Views: 263

Answers (2)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

As far as I know back_trace is the best way. That said, if you want to get the class / file etc that called a script you can use this function

 /**
 * get the line this file was called on ( +1 )
 * @param number $offset
 * @return array
 */
function trace($offset = 0)
{
    $trace = debug_backtrace(false);
    foreach ($trace as $t) {
        if ($t['file'] != __FILE__) {
            break;
        }
        ++$offset;
    }
    return array_slice($trace, ($offset - count($trace)));
}

Basically as you iterate through the backtrace, you're looking for the item before the current file.

You can also set $offset if you want it say 1 location before the one that called the trace() function.

https://github.com/ArtisticPhoenix/Evo/blob/master/Evo/Debug.php

Upvotes: 2

RudiBR
RudiBR

Reputation: 117

If you just want the current class name, you can use get_class(); If the call stack involves many classes, and you want the first one for example, then you really have to use debug_backtrace().

$className = get_class($this);

Upvotes: 2

Related Questions