PHP扩展异常

时间:2014-08-24 13:39:16

标签: php exception-handling

在下面的代码示例中,我试图让类名Volvo出现在异常消息中,但出现的是CarException。在抛出异常时,如何在未指定__CLASS__的情况下将类名Volvo出现在异常消息中?

    class Volvo extends Car {
        public function smash() {
            throw new CarException("This car doesn't really smash.");
        }
    }

    abstract class Car {
        public function __construct() {
            var_dump(get_called_class());
        }
    }

    class CarException extends \Exception {
        public function __construct($message, $code = 0, Exception $previous = null) {
            $message = get_called_class() . ": $message";
            parent::__construct($message, $code, $previous);
        }
    }

    $volvo = new Volvo();
    try {
        $volvo->smash();
    } catch (CarException $e) {
        var_dump($e->getMessage());
    }

1 个答案:

答案 0 :(得分:0)

如果我理解你,你正在寻找getTrace

class CarException extends \Exception {
    public function __construct($message, $code = 0, Exception $previous = null) {
        $trace = $this->getTrace();
        $cls = $trace[0]['class'];
        $message = $cls . ": $message";
        parent::__construct($message, $code, $previous);
    }
}

get_called_class不适用于此:它返回“拥有”代码的类的名称,而不是“调用”代码的类。