Apps

10 improvements in PHP 5.5.0 for web developers

Here are examples of some new features and improvements in the latest release of PHP.

PHP 5.5.0 has been released, bringing with it a host of new features and fixes. TechRepublic has rounded up 10 improvements that web developers should look out for in the new release.

One key difference to note before upgrading is that support for Windows XP and 2003 has been dropped as of 5.5.0. Other backwardly incompatible changes introduced by the release can be found here.

#1 Generators are now available

Generators provide a simple way to iterate through data without having to write a class implementing the Iterator interface.

Just like any other function a generator is defined with the function keyword, but unlike a normal function that just returns a result once, a generator can send back as many results as needed using the yield keyword.

A simple example of using a generator function to print out a positive sequence of integers is shown below.

function xrange($start, $end, $step = 1) {
for ($i = $start; $i <= $end; $i += $step) {
yield $i;
}
}
echo 'Single digit odd numbers: ';
foreach (xrange(1, 9, 2) as $number) {
echo "$number ";
}
echo "\n";

This would print "Single digit odd numbers:1,3,5,7,9".

A generator allows you to iterate over a set of data using a foreach loop without needing to build an array in memory. Not having to create an array reduces memory usage and processing time.

For example, using the range() function to generate a sequence between one and one million by calling range(0,1000000) within a foreach loop will create an array of more than 100MB in size, according to the PHP Manual. In comparison, creating a sequence using a generator function will never need to consume more than 1KB.

#2 Finally keyword added

The addition of the "finally" keyword refines the way that PHP deals with exception handling.

Like other high level languages PHP allows you to wrap code in a try and catch block. Any exception that is thrown by code within the try block will be passed to code within the catch block to be handled.

The finally keyword allows you to define a block of code, to be placed after the catch block, that will always be executed after the try and catch blocks, regardless of whether an exception was thrown.

The PHP manual gives this example:

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}
try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "First finally.\n";
}

#3 New password hashing API

The new password hashing API allows you to use one line of code to generate a salted password hash using bcrypt. For example:

$hash = password_hash($password, PASSWORD_DEFAULT);

password_hash() takes two arguments here, first the password as a string and second a constant setting the encryption algorithm to use.

The password will be automatically salted and can be verified using the following code:

 password_verify($password, $hash);

The current default encryption algorithm used is bcrypt, although this is expected to change as new and stronger algorithms are added to PHP.

It is recommended to store the result in a database column that can expand beyond 60 characters.

#4 Array and string literal deferencing added

Both array and string literals can now be dereferenced directly to access individual elements and characters.

For example:

echo 'Array dereferencing:';
echo [4,5,6][0];
echo "\n";

selects the first element in the array to be printed, producing "Array dereferencing:4".

echo 'String dereferencing:';
echo 'HELLO'[0];
echo "\n";

selects the first element in the string to be printed, producing "String dereferencing:H".

#5 Easier class name resolution

The class keyword can now be used to retrieve the fully qualified name of a class, including the namespace it sits within.

For example:

namespace NS {
    class ClassName {
    }
    echo ClassName::class;
}

will print out the both the name of the class and the namespace, producing "NS\ClassName".

#6 Empty() function accepts expressions

The empty() function, used to determine whether a variable is empty or a value equals false, can now be passed an expression and determine whether the variable that expression returns is empty.

For example:

function send_false() {
    return false;
}
if (empty(send_false())) {
    echo "False value returned.\n";
}
if (empty(true)) {
    echo "True.\n";
}

will print "False value returned."

#7 Support for the Zend Optimiser+ opcode cache added

The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension.

OPcache improves performance of scripts by removing the need for PHP to load and parse scripts every time a request is made. It achieves this by storing precompiled script bytecode in shared memory.

#8 foreach loops now support the list() construct

Values insides nested arrays can now be assigned to variables using a foreach() loop and the list() construct.

List() can be used to easily assign values taken from inside an array to variables, like so:

$animals = array('dog', 'fox');
// Listing all the variables
list($animal1, $animal2) = $animals;
echo "The quick $animal1 jumped over the lazy $animal2\n";

to produce the familiar, "The quick fox jumped over the lazy dog".

Now list() can be used with foreach() loops to be assigned values from inside nested arrays, for example:

$array = [
    [10, 20],
    [30, 40],
];
foreach ($array as list($a, $b)) {
    echo "First: $a; Second: $b\n";
}

to produce:

First: 10, Second: 20

First: 30, Second: 40

#9 New features added to GD library

PHP's GD extension for creating and manipulating images has gained new capabilities. These include flipping support using the new imageflip() function, advanced cropping support using the imagecrop() and imagecropauto() functions, and WebP read and write support using the imagecreatefromwebp() and imagewebp() functions.

#10 foreach loops now support non-scalar keys

When iterating through an array using a foreach loop, element keys are now able to have a non-scalar value, that is a value other than an integer or a string.

Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.

About

Nick Heath is chief reporter for TechRepublic UK. He writes about the technology that IT-decision makers need to know about, and the latest happenings in the European tech scene.

4 comments
ZachS.
ZachS.

thanks for the interesting article!

Xennex1170
Xennex1170

FYI, the correct phrase is "The Quick Brown Fox Jumps over the Lazy Dog".. This is the line famous for having all 26 letters of the alphabet. (^_^)

celinsmith111
celinsmith111

PHP new update has many good feature, which short out developer problem, exception handling is major from it.

TimMartin01
TimMartin01

Exception handling is the great feature and there many more features also available as an high level language have.

Editor's Picks