Jay Bhatt
Jay Bhatt

Reputation: 5651

Code confusion while extending PHP exception class

This question is related to extending the PHP exception class and there are many similar questions but this one is different.

I am trying to extend the PHP exception class so I can add certain values to the exception message. Below is my code.

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

}

This works fine. And that is my problem.

Since I am calling the functions getLine() and getFile() of the parent class before calling its constructor shouldn't they return blank values? if not error?

But this works fine and I get the output described below.

Exception => hello..
Class => Om_Controller_Exception
Error Line => 30
Error File => C:\Users\Jay\Projects\order-manager\application\modules\default\controllers\LoginController.php 

Can anyone please help me understand why this behavior? How can I use class methods before initializing the class?

Upvotes: 1

Views: 100

Answers (1)

Bing
Bing

Reputation: 746

The constructor is called on a newly created object, so the object and all it's properties and methods already exists when the constructor is called. This example should make it pretty clear:

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

Result

testChild

testParent

The number is now: 1

The number is now: 42

Upvotes: 2

Related Questions