开发者

dynamic access magic constants in php

Is there a way to shortcut this:

function a($where){
  echo $where;
}

function b(){
  a(basename(__FILE__).'::'.__FUNCTION__.'()::'.__LINE__);
}

to something like this:

    define("__myLocation__", ''.basename(__FILE__).'::'.__FUNCTION__.'()::'.__LINE__.'');
    function a($where){
      echo $where;
    }

    function b(){
      a(__mYLocation_);
    }

I know that this cannot be done with constants (is just an theoretic开发者_Go百科al example), but I can't find a way to shorthen my code. If a use a function to get my line it will get the line where that function is not the line from where the function was called.

I usualy call a function that prints directly to the log file, but in my log I need to know from where the function was called, so i use basename(__FILE__).'::'.__FUNCTION__.'()::'.__LINE__ this will print something like:

index.php::b()::6

It is a lot of code when you have over 500 functions in different files. Is there a shorten or better way to do this?


debug_backtrace() should help you, although I don't know what the performance hit would be making a call to it every log you cut. Try this:

function cut_log() {
    $trace = debug_backtrace();
    echo basename($trace[1]['file']) . '::' . $trace[1]['function']
         . '::' . $trace[1]['line'];
}

function a() {
    cut_log();
}

a();


Ehh.. I guess you could do that with eval and that constant.

define("__myLocation__", "''.basename(__FILE__).'::'.__FUNCTION__.'()::'.__LINE__.''");
function a($where){
  echo $where;
}

function b(){
  a(eval(__myLocation__));
}

But you really shouldn't be using eval for anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜