获取在PHP中执行当前功能的代码行和文件?

编程入门 行业动态 更新时间:2024-10-25 12:24:27
本文介绍了获取在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().

us3.php/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中执行当前功能的代码行和文件?

本文发布于:2023-11-10 02:02:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574046.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   功能   文件   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!