Tom Tom - 3 months ago 11
PHP Question

Get code line and file that's executing the current function in PHP?

Imagine I have the following situation:

File1.php

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


Function.php

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


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


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


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

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


TestClass.class.php

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


Logger.static.php

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


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?

Answer

You can use debug_backtrace().

http://us3.php.net/manual/en/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.

Here's a quick example:

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

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

  // do your logging stuff here.    
}
Comments