【问题标题】:Get filename and line number of start of function declaration [duplicate]获取函数声明开始的文件名和行号[重复]
【发布时间】:2011-11-02 14:23:40
【问题描述】:

可能重复:
How to find out where a function is defined?
included php file to know it's file name?

我可以在 PHP 中获取函数声明开头的文件名行号吗?

说,我有以下代码:

 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. }

当我调用foo_bar("none") 时,函数必须抛出如下错误:

警告:第 4 行 /home/web/mcemperor 中的“foo_bar()”参数错误。

我可以检索函数声明开始的文件名行号吗?

【问题讨论】:

  • @CodeCaster:不同意那个副本。这是关于知道函数定义所在的行和文件,而不是我们所在文件的文件名......
  • @ircmaxell 他想要一个函数本身(正在执行,所以设置了__FILE____LINE__)来显示它的位置。

标签: php function


【解决方案1】:

您正在寻找ReflectionFunction

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

就这么简单...它适用于任何已定义的函数,无论您传递给构造函数参数的任何函数。

【讨论】:

  • 正是,我在找什么,谢谢:)
【解决方案2】:

函数名可以在 PHP 异常中找到,对于错误触发更有趣:http://www.php.net/manual/en/exception.gettrace.php

【讨论】:

    【解决方案3】:
    $backtrace = debug_backtrace();
    $line = $backtrace[0]['line'];
    $file = $backtrace[0]['file'];
    

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

    【讨论】:

    • __LINE__ 是当前行,而不是“函数声明开始的行号”
    • 公平点。添加了另一种方法。
    • 同理:“行-整数-当前行号。” php.net/manual/en/function.debug-backtrace.php
    • 当前取决于上下文,尽管我确实以错误的方式获得了我的数组索引。请参阅第一个示例中的第零个元素。 ["file"] => string(10) "/tmp/a.php" ["line"] => int(10)
    猜你喜欢
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-17
    • 1970-01-01
    • 1970-01-01
    • 2018-01-06
    相关资源
    最近更新 更多