获取在PHP中执行当前功能的代码行和文件? [英] Get code line and file that's executing the current function in PHP?

查看:238
本文介绍了获取在PHP中执行当前功能的代码行和文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有以下情况:

Imagine I have the following situation:

File1.php

File1.php

<?php
 include("Function.php");
 log("test");
?>

Function.php

Function.php

<?php
 function log($msg)
 {
  echo "";
 }
?>

我想更改日志功能,以便产生以下内容:

I want to change the log function so that it would produce the following:

测试(文件:File1.php,行号:3)

test (file: File1.php, line number: 3)

那么,有什么方法可以获取在PHP中执行当前功能的代码的文件名和行号?

So, any way to get the file name and the line number of the code that executed the current function in PHP?

编辑积压用法注释: 当我以面向对象的编程方式使用积压时,会遇到以下情况.

EDIT for backlog usage comments: When I use backlog in my object oriented way of programming I have the following situation.

Index.php

Index.php

<?php
 include("Logger.static.php");
 include("TestClass.class.php");
 new TestClass();
?>

TestClass.class.php

TestClass.class.php

<?php
 class TestClass
 {
   function __construct()
   {
     Logger::log("this is a test log message");
   }
 }
?>

Logger.static.php

Logger.static.php

<?php
 class Logger
 {
   static public function log($msg)
   {
     $bt = debug_backtrace();
     $caller = array_shift($bt);
     echo $caller['file'];
     echo $caller['line'];
   }
 }
?>

此示例将以文件"Index.php"和第4行返回,这是该类的起始位置.但是,应该返回文件TestClass.class.php和第6行.您知道如何解决此问题吗?

This example will return as file "Index.php" and as line number 4, this is where the class is initiated. However, it is supposed to return the file TestClass.class.php and line number 6. Any idea how to fix this?

推荐答案

您可以使用debug_backtrace().

You can use debug_backtrace().

http://us3.php.net/manual/zh/function.debug-backtrace.php

因此,在您的日志功能中,您将能够检索调用日志功能的文件名和行号.

So, in your log function, you would be able to retrieve the filename and line number from which the log function was called.

我在日志记录类中使用了这种方法,它大大减少了获取有意义的日志数据所需的代码量.另一个好处是可读性.与字符串混合时,魔术常数会变得非常难看.

I'm using this approach in my logging classes and it has significantly reduced the amount of code required to get meaningful log data. Another benefit would be readability. Magic constants tend to get quite ugly when mixed with strings.

这是一个简单的例子:

function log($msg)
{
  $bt = debug_backtrace();
  $caller = array_shift($bt);

  // echo $caller['file'];
  // echo $caller['line'];

  // do your logging stuff here.    
}

这篇关于获取在PHP中执行当前功能的代码行和文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆