想象一下我有以下情况:
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中执行当前功能的代码行和文件?
发布评论