【问题标题】:Exception get line where method is accessed PHP访问方法的异常获取行 PHP
【发布时间】:2012-11-27 16:04:30
【问题描述】:

如何获取访问方法的行?

方法:

function configure($newFile = false){

    try {

        ...
        throw new Exception("Error X");

    } catch (Exception $e) {

        $exception = "<b>Caught exception: </b>\n<blockquote>"
            .$e->getMessage()
            ."</blockquote>"
            ."\n"."on line <b>"
            .$e->getLine()
            ."</b> of <i>"
            .$e->getFile()
            ."</i>";

        echo $exception;

    }

}

输出是这样的:

Caught exception:
Error X
on line 25 of C:\xampp\htdocs\MgFramework\classes\MgDatabase.class.php

但我想显示访问该方法的行和文件:

$database = new MgDatabase();
$database->configure();

有可能吗?

谢谢!

【问题讨论】:

  • Psst,你可能想read the Exception class manual page,因为它列出了所有可用的方法。其中一个或多个是您正在寻找的。​​span>
  • 答案隐藏在每个异常对象中可用的堆栈跟踪中。

标签: php exception throw


【解决方案1】:

我只需要访问 getTrace() 方法。

它返回一个二维数组,其中包含所有到 throw 的踪迹。

【讨论】:

    【解决方案2】:
    class YourClass extends Exception
        {
            /**
             * can use
             * $this->line
             *
             * only __construct and __toString are not final
             *
             * @link http://php.net/manual/en/class.exception.php
             *  */
            function SomeMethod()
            {
                return "that is mine one: " . $this->line; // Exception extends variable access to protected variable $line
            }
            function AnotherMethod(Exception $e)
            {
                return $e->getLine() . " – " . $e->getFile();
            }
            function ThirdMethod($l,$f)
            {
                return $l . " – " . $f;
            }
        }
    
        $test = new YourClass;
        print $test->getLine(); // Exception extends method
    
        print "<hr>";
        print $test->SomeMethod(); // your class Method
    
        print "<hr>";
        print $test->AnotherMethod(new Exception()); // new Exception
    
        print "<hr>";
        print $test->ThirdMethod(__LINE__,__FILE__); // magic constant __LINE__ and __FILE__
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-01
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 2018-08-08
      • 1970-01-01
      • 1970-01-01
      • 2018-08-31
      相关资源
      最近更新 更多