Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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? Not for debugging purposes. It has the word "debug" in the function name, which makes me feel a little dirty to be using it in this way, but it fit the bill for what I needed to do (a single function that can be called from many places and needs to call the calling method from another system). It works, but is this still a bad idea? If so, why?

like image 872
Sydius Avatar asked Dec 06 '08 20:12

Sydius


People also ask

What is the Backtrace in PHP?

Definition and UsageThe debug_backtrace() function generates a PHP backtrace. This function displays data from the code that led up to the debug_backtrace() function. The current call type.

How do I get PHP to produce a Backtrace upon error?

For more advanced solution, you can use XDebug extension for PHP. By default when XDebug is loaded, it should show you automatically the backtrace in case of any fatal error. Or you trace into file (xdebug. auto_trace) to have a very big backtrace of the whole request or do the profiling (xdebug.

What is stack trace PHP?

So the stack trace is a list of the functions in the call stack at the point an exception is triggered. Throwing an exception is how the interpreter tells you an error has happened. This could be from a mistyped variable, incorrect input, or any type of exception that you've defined in your code.


1 Answers

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.

like image 104
Alan Storm Avatar answered Sep 25 '22 01:09

Alan Storm