Jan 10 2010
Built-in Exception changes in PHP 5.3
What really changes in built-in Exception class in PHP 5.3?
- added third parameter $previous to constructor: Exception::__construct,
- added method Exception::getPrevious to retrieve $previous property.
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 = 0, Exception $previous = null)
{
parent::__construct($message, $code);
if ( !is_null($previous) )
{
$this->previous = $previous;
}
}
/**
* @return Exception
*/
public function getPrevious()
{
return $this->previous;
}
}
Comments Off