Forum Moderators: coopster

Message Too Old, No Replies

How to get file and line number where a function is called?

         

dbzfyam

1:43 pm on May 26, 2009 (gmt 0)

10+ Year Member



Does anyone know if it's possible to get the file and the line number from where a function is called?
I have something like this:

require_once('libs/class.db.php');
$db = new database(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$aQueryResults = $db->query('SELECT....');

If that query fails, I echo a error like this:

echo $sql." failed in ".__file__." on line ".__line__;

This however always points to the included file (class.db.php). So instead, I want to show the filename where the include is and the line number where I query the database.

Is this possible?

Thanks in advance!

coopster

1:49 pm on May 26, 2009 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



You can throw and catch [php.net] errors. The technique allows you to see the trace stack.

idfer

2:08 pm on May 26, 2009 (gmt 0)

10+ Year Member



I wrote this a long time ago for my logging class, it might help you out (i've modified it a bit for this post but not tested the modifications):


// Returns the function name that called for logging.
// Returns ? if function name can't be determined.
// Uses stack dump to find function name.
//
function getFunc() {
$stack = debug_backtrace();
$n = 0;

// Skip over own functions.
while($n < count($stack)
&& basename($stack[$n]['file']) == basename(__FILE__))
$n++;

if($n >= count($stack)) {
// No other function found.
$func = '?';

} elseif(isset($stack[$n+1])) {
// Function call.
$c = $stack[$n+1];
if(!empty($c['class']))
$class = $c['class'];
else
$class = $stack[$n]['file'].':'.$stack[$n]['line'].',';
$func = $class.@$c['type'].$c['function'];

} else {
// Direct from script file.
$c = $stack[$n];
$func = $stack[$n]['file'].':'.$stack[$n]['line'];
}

return $func;
}

dbzfyam

4:13 pm on May 26, 2009 (gmt 0)

10+ Year Member



Thanks for the quick replies! Just tried your idfer's script and it works great. Have to look into throw and catch aswell. Looks usefull. Thanks you both for the help!