PHP debug_backtrace in production code to get information about calling method?

Is there a compelling reason to not use debug_backtrace for the sole purpose of determining the calling method's class, name, and parameter list?

Yes. The point is, it's generally a sign of bad design if your code requires such a tight coupling that the callee has to have these information about its caller because it breaks referential transparency. Therefore, if you feel the need to use these information, you probably should rethink your design.

The callee should not need to have these information to perform its task. The exceptions, of course, revolve around debugging, logging and more generally other kinds of code introspection (but even there, beware of it).


It does feel a little dirty, but as has been well documented, opined, and beaten to death elsewhere, PHP isn't a system designed for elegance.

One highly convoluted reason not to use debug_backtrace for application logic is it's possible some future developer working on PHP could decide "it's just a debug function, performance doesn't matter".

If you're interested in a "better" way of doing this, you could probably use PHP's magic constants to pass in the calling method and class name, and then use a ReflectionMethod object to extract any other information you need.

I put better in quotes because, while this would be cleaner and more correct, the overhead of instantiating a Reflection object may be greater than using the debug_backtrace function.

Tags:

Php