异常获取访问方法的行PHP

时间:2012-12-10 08:50:43

标签: php exception throw

如何获取访问方法的行?

方法:

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();

有可能吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

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

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

答案 1 :(得分:0)

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__