Jan 10 2010

Built-in Exception changes in PHP 5.3

Tag: English,PHPJens @ 23:00

What really changes in built-in Exception class in PHP 5.3?

It is useful to use Java like nesting exceptions in PHP. In following example, we catch data insert exception (in class which is inherited from Zend_Db_Table) and throws own defined (Jens_Db_Exception) exception. We have still full information about previous (Zend_Db_Exception) exception.

try {
    $this->insert($some_data);
}
catch ( Zend_Db_Exception $e ) {
    throw new Jens_Db_Exception('Insert failed'0$e);
}

In PHP 5.2, we can use simple extension of built-in Exception to provide functionality described above:

class Jens_Exception extends Exception
{
    /**
     * @var Exception
     */
    private $previous;

    /**
     * @param string $message
     * @param int $code
     * @param Exception $previous
     */      
    public function __construct($message$code 0Exception $previous null)
    {
        parent::__construct($message$code);

        if ( !is_null($previous) )
        {
            $this->previous $previous;
        }
    }

    /**
     * @return Exception
     */
    public function getPrevious()
    {
        return $this->previous;
    }
}