Wednesday, 5 December 2012

Features of PHP 5

Language Features
For a more complete example, see Chapter 4, “PHP 5 Advanced OOP and
Design Patterns.”
☞__autoload().
Many developers writing object-oriented applications create one PHP
source file per class definition. One of the biggest annoyances is having to
write a long list of needed inclusions at the beginning of each script (one for
each class). In PHP 5, this is no longer necessary. You may define an
__autoload()function that is automatically called in case you are trying to use
a class that has not been defined yet. By calling this function, the scripting
engine offers one last chance to load the class before PHP bails out with an
error:
function __autoload($class_name) {
include_once($class_name . "php");
}
$obj = new MyClass1();
$obj2 = new MyClass2();
Other New Language Features
☞Exception handling.
PHP 5 adds the ability for the well-known try/throw/catchstructured
exception-handling paradigm. You are only allowed to throw objects that
inherit from the Exceptionclass:
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 backward-compatibility purposes, most internal functions
do not throw exceptions. However, new extensions make use of this capability,
and you can use it in your own source code. Also, similar to the already exist-ing set_error_handler(), you may use set_exception_handler()to catch an
unhandled exception before the script terminates.
Gutmans_Ch01 Page 7 Thursday, September 23, 2004 2:35 PM
8  What Is New in PHP 5? Chap. 1
☞foreachwith references.
In PHP 4, you could not iterate through an array and modify its values.
PHP 5 supports this by enabling you to mark the foreach()loop with the
&(reference) sign, which makes any values you change affect the array
over which you are iterating:
foreach ($array as &$value) {
if ($value === "NULL") {
$value = NULL;
}
}
☞Default values for by-reference parameters.
In PHP 4, default values could be given only to parameters, which are
passed by-values. PHP 5 now supports giving default values to by-reference parameters:
function my_func(&$arg = null) {
if ($arg === NULL) {
print '$arg is empty';
}
}
my_func();

No comments:

Post a Comment