New Object Oriented Features - By PHP Expert


Exception handling
PHP 5 adds the ability for the well known try/throw/catch structured exception handling paradigm. You are only allowed to throw objects which inherit from the Exception class.

class SQLException extends Exception {
public $problem;
function __construct($problem) {
$this->problem = $problem;
}
}

try {
...
throw new SQLException("Couldn't connect to database");
...
} catch (SQLException $e) {
print "Caught an SQLException with problem $obj->problem";
} catch (Exception $e) {
print "Caught unrecognized exception";
}

Currently for backwards compatibility purposes most internal functions do not throw exceptions. However, new extensions are making use of this capability and you can use it in your own source code. Also, similar to the already existing set_error_handler() you may use set_exception_handler() to catch an unhandled exception before the script terminates.

foreach with references
In PHP 4, you could not iterate through an array and modify its values. PHP 5 supports this by allowing you to mark the foreach() loop with the & (reference) sign, thus making any values you change affect the array you're iterating over.
foreach ($array as &$value) {
if ($value === "NULL") {
$value = NULL;
}
}

default values for by-reference parameters
In PHP 4, default values could only be given to parameters which are passed by-value. Giving default values to by-reference parameters is now supported.

function my_func(&$arg = null) {
if ($arg === NULL) {
print '$arg is empty';
}
}
my_func();

No comments