about me about me
photography photography
software projects software projects
contact me contact me
10
Sep

PHP4 Exceptions

posted 2006 // Uncategorized // 0

During the last project I worked on, before moving companies, I would often want to pass back more error information from methods than primitive types would allow. What I wanted was a PHP4 exception. You’ll need PHP 4.3.0 or above for this class to work.

[sourcecode language="php"]
class Error {

var $message;
var $code;
var $file;
var $line;
var $trace;

function Error($message = null, $code = 0) {

$this->message = $message;
$this->code = $code;
$this->trace = (phpversion() >= 4.3) ? debug_backtrace() : array();

}

function getMessage() {

return $this->message;

}

function getCode() {

return $this->code;

}

function getFile() {

return $this->trace['file'];

}

function getLine() {

return $this->trace['line'];

}

function getTrace() {

reset($this->trace);
return current($this->trace);

}

function getArgs() {

reset($this->trace);
$trace = current($this->trace);
return $trace['args'];

}

}
[/sourcecode]

I then created the following function to identify when the Error class was returned:

[sourcecode language="php"]
function isError($result) {

return (is_a($result,’Error’) ? true : false);

}
[/sourcecode]

I would then use it like so:

[sourcecode language="php"]
class OrderDB {

function save() {

if (!$this->db->query(
‘UPDATE orders SET … WHERE order_id = ‘ . $this->order->getId())) {
return new Error(‘Failed to update order ‘ . $this->order->getId());
} else {
return true;
}

}

}
[/sourcecode]

Mimicking a try catch block:

[sourcecode language="php"]
$saveResult = $orderDb->save();

if ($saveResult) {

} else if (isError($saveResult)) {
$logger = $this->locator->get(‘log’);
$logger->log(‘Error occured in ‘ . $saveResult->getFile() . ‘ on line ‘ . $saveResult->getLine() . ‘: ‘ . $saveResult->getMessage());

}
[/sourcecode]

An obvious short coming of this solution is that every result must be checked whereas a true try catch statement will catch any exception thrown within the try block. On the plus side you can still extend the Error class and isError will recognise you’ve returned a child of the Error class.

Typically 2 minutes Googling reveals a beefed up PHP4 exception class.

You can skip to the end and leave a response. Pinging is currently not allowed.

comments

No comments for this post. Be the first to respond!




this post's tags