ds2321 2010-05-20 18:30
浏览 35
已采纳

PHP函数:查找参数的变量名,函数调用行号

I want to do something like this for simplifying logging operations. Any idea what I should put in for ?[1]? and ?[2]??

function log_var($var) {
  $line = ?[1]?;
  $var_name = ?[2]?;

  $line--;

  $filepath = 'log-' . date('Y-m-d'). '.txt';
  $message  = "$line, $var_name = $var
";
  $fp = fopen($filepath, "a");
  fwrite($fp, $message);
  fclose($fp);
  @chmod($filepath, 0666);
  return TRUE;
}

This how I'd use the function in code (numbers are assumed to be line numbers in actual code):

23  $a = 'hello';
24  log_var($a);
25  $b = 'bye';
26  log_var($b);

And this is what I want to be written to the log file:

23, a = hello
25, b = bye

EDIT I converted Paul Dixon function a bit and added the result as an answer. The new form does even MORE than I originally hoped for. Thank you again guys!

  • 写回答

6条回答 默认 最新

  • dqlm80253 2010-05-20 18:38
    关注

    This isn't something you can easily do, as the function parameter is an expression which is evaluated before the function is called. Thus, the function can only see the value of that expression, and not the expression itself.

    If you really want to do this, you could use debug_backtrace to find the file and line number of the caller, extract that line from the source file, then parse out the expression from the function call. Here's a proof-of-concept:

    function dump($value)
    {
        $trace=debug_backtrace();
        $expr="<unknown>";
        if (isset($trace[0]['file']))
        {
            $lines=file($trace[0]['file']);
            $line=$lines[$trace[0]['line']-1];
            $expr=$line;
            $expr=preg_replace('/\s*dump\(/i','', $expr);
            $expr=preg_replace('/\);\s*/', '', $expr);
    
        }
    
        echo "$expr is $value
    ";
    }
    
    //examples...
    $a=10;
    dump($a);
    
    dump($a+10);
    

    Clearly nuts. But it works :) You could of course simply pass the name in along with the variable!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 等差数列中的素数个数
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证