扩展PHP异常类时的代码混乱

扩展PHP异常类时的代码混乱,php,exception,exception-handling,Php,Exception,Exception Handling,这个问题与扩展PHP异常类有关,有许多类似的问题,但这个问题不同 我试图扩展PHP异常类,以便可以向异常消息添加某些值。下面是我的代码 class Om_Exception extends Exception { public function __construct($message, $code = 0, Exception $previous = null) { $message = $this->_getMessage($message);

这个问题与扩展PHP异常类有关,有许多类似的问题,但这个问题不同

我试图扩展PHP异常类,以便可以向异常消息添加某些值。下面是我的代码

class Om_Exception extends Exception {

    public function __construct($message, $code = 0, Exception $previous = null) {
        $message = $this->_getMessage($message);
        parent::__construct($message, $code, $previous);
    }

    protected function _getMessage($message) {
        $exception = '<br />';
        $exception .= '<b>Exception  => </b>'.$message.'<br />';
        $exception .= '<b>Class => </b>'.get_called_class().'<br />';
        $exception .= '<b>Error Line => </b>'.$this->getLine().'<br />';
        $exception .= '<b>Error File => </b>'.$this->getFile().'<br />';
        return $exception;
    }

}

有人能帮我理解为什么会有这种行为吗?初始化类之前如何使用类方法?

在新创建的对象上调用构造函数,因此调用构造函数时对象及其所有属性和方法都已存在。这个例子应该非常清楚:

<?php

class testParent {
    protected $protectedStuff = 1;
    public function __construct($intNumber) {
        $this->protectedStuff = $intNumber;
    }
}
class testChild extends testParent {
    public function __construct($intNumber) {
        echo get_class() . '<br />'; // testChild
        echo get_parent_class() . '<br />'; // testParent
        $this->printStuff(); // 1
        parent::__construct($intNumber);
        $this->printStuff(); // 42
    }
    public function printStuff() {
        echo '<br />The number is now: ' . $this->protectedStuff;
    }
}
$objChild = new testChild(42);

你说的“调用构造函数之前”是什么意思?您的类具有构造函数,它显式调用父类constructor@AlmaDo在调用父构造函数之前,先调用getMessage()方法,该方法调用父类的getLine()和getFile()方法。那又怎样?您的方法将被继承,它们的实现也将被继承。因此,您的调用将使用标准的
Exception
methods构造函数初始化属性,而不是方法。您可以在父构造函数之前调用任何方法,除非它不使用未初始化的属性
Exception
是PHP中的一个特殊内置类。在执行构造函数之前,将填充
$code
$file
$line
属性。
<?php

class testParent {
    protected $protectedStuff = 1;
    public function __construct($intNumber) {
        $this->protectedStuff = $intNumber;
    }
}
class testChild extends testParent {
    public function __construct($intNumber) {
        echo get_class() . '<br />'; // testChild
        echo get_parent_class() . '<br />'; // testParent
        $this->printStuff(); // 1
        parent::__construct($intNumber);
        $this->printStuff(); // 42
    }
    public function printStuff() {
        echo '<br />The number is now: ' . $this->protectedStuff;
    }
}
$objChild = new testChild(42);