3

Possible Duplicate:
How to find out where a function is defined?
included php file to know it's file name?

Can I get the filename and line number of the start of a function declaration in PHP?

Say, I have the following code:

 1. /**
 2.  * This function shows the foo bar.
 3.  */
 4. function foo_bar($subject) {
 5.     echo "Foo bar:\n";
 6.     if ($subject == "none") {
 7.         trigger_error("Wrong argument given to 'foo_bar()' in ... on line ....", E_USER_WARNING);
 8.     }
 9.     ...
10. }

When I call foo_bar("none"), the function must throw an error like this:

Warning: Wrong argument given to 'foo_bar()' in /home/web/mcemperor on line 4.

Can I retrieve the filename and the line number of start of the function declaration?

Community
  • 1
  • 1
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
  • 2
    @CodeCaster: disagree with that duplicate. This is about knowing the line and file of where a function's defined, not the file name of the file that we're in... – ircmaxell Nov 02 '11 at 14:28
  • @ircmaxell he wants a function itself (which is being executed, so `__FILE__` and `__LINE__` are set) to show where it is. – CodeCaster Nov 02 '11 at 14:30

3 Answers3

12

You're looking for ReflectionFunction.

$r = new ReflectionFunction('foo_bar');
$file = $r->getFileName();
$startLine = $r->getStartLine();

It's that simple... It works for any defined function, whatever one that you passed in to the constructor argument.

ircmaxell
  • 163,128
  • 34
  • 264
  • 314
0
$backtrace = debug_backtrace();
$line = $backtrace[0]['line'];
$file = $backtrace[0]['file'];

http://www.php.net/manual/en/function.debug-backtrace.php

Ben Swinburne
  • 25,669
  • 10
  • 69
  • 108
0

The function name could be found with PHP exceptions, which are more interesting for error triggering : http://www.php.net/manual/en/exception.gettrace.php

Fedir RYKHTIK
  • 9,844
  • 6
  • 58
  • 68