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

后端 未结 7 961
野趣味
野趣味 2020-11-29 05:43

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

7条回答
  •  無奈伤痛
    2020-11-29 06:23

    The correct answer is that it is totally OK. Alan points the non elegance of PHP, so I won't reiterate his points. The reason to (not be afraid to) use debug_backtrace in runtime code is because PHP is mostly a context free language. Each function does not know about, nor can know the caller's "intention" without using magic function names (for instance in a class -- e.g. __toString()) with casting. Lets consider the case where you have a class, in which (in a method), you want to provide access to calling (outer) class's properties. It is truly messy and prone to errors to pass ($this) around through the function API. (Especially when you want to array_map or call_user_func_array.)

    e.g.

    
    

    The debug_backtrace will give you access to the context of class a in the __construct of b. Now you can pass some state variables from the current class without passing $this around or trying to divine it from class names or kludge it by putting it into globals.

    For those that are interested in the time, microtime was 2.7E-5 . Fast enough. Just don't put it in a while(1).

提交回复
热议问题