4
Php

Php 5.5.x and New Features

On 20-Jun-2013, the PHP development team has announced the immediate availability of PHP 5.5.0 and this release includes a large number of new features and bug fixes. The new features of PHP 5.5.0 includes :

Generators :

Support for generators has been added via the yield keyword. Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface. For example:

function xrange($start, $limit, $step = 1)
{
    for ($i = $start; $i <= $limit; $i += $step) {
        yield $i;
    }
}
// Note that an array is never created
// or returned, which saves memory.
echo 'Single digit odd numbers: ';
foreach (xrange(1, 9, 2) as $number) {
    echo "$number ";
}
// Output :
/**
  * Single digit odd numbers: 1 3 5 7 9
  */

It looks like that, the yield keyword is working like the return keyword but it's not terminating the execution of the current process, instead, it returns a value and continues.

New finally Keyword :

In PHP 5.5.0 the finally block may also be specified after the catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes. For example:

function inverse($x) {
    if (!$x) {
        throw new Exception('Division by zero.');
    }
    return 1/$x;
}
// First block no exceptions
try {
    echo inverse(5) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "First finally.\n";
}
// Second block with an exceptio
try {
    echo inverse(0) . "\n";
} catch (Exception $e) {
    echo 'Caught exception: ',  $e->getMessage(), "\n";
} finally {
    echo "Second finally.\n";
}
// Continue execution
echo "Hello World";

// Output :
/**
 * 0.2
 * First finally.
 * Caught exception: Division by zero.
 * Second finally.
 * Hello World
 */
New password hashing API :

A new password hashing API that makes it easier to securely hash and manage passwords using the same underlying library as crypt() in PHP has been added. The new password hashing API allows you to use one line of code to generate a salted password hash using Bcrypt. For example:

// The password will be automatically salted
$hash = password_hash('mypassword', PASSWORD_DEFAULT);

The password_hash takes three arguments and the third one is optional. First argument is the plain password to be hashed, the second argument is a password algorithm constant denoting the algorithm to use when hashing the password and the third one is an associative array containing options. Currently, two options are supported: salt, to provide a salt to use when hashing the password, and cost, which denotes the algorithmic cost that should be used. If omitted, a random salt will be created and the default cost will be used. For example, with options :

// Setting the option to increase the default cost for BCRYPT to 12
$options = [
    'cost' => 12,
];
// The password algorithm is switched to BCRYPT
echo password_hash("mypassword", PASSWORD_BCRYPT, $options)."\n";

The current default encryption algorithm used is Bcrypt (default as of PHP 5.5.0), although this is expected to change as new and stronger algorithms are added to PHP. It is recommended to keep the password field length at least 60 characters in the database but 255 would be good.

This is another example with cost and salt (randomly generated salt) options :

// Setting the cost and salt manually
$options = [
    'cost' => 11,
    'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM),
];
echo password_hash("mypasscword", PASSWORD_BCRYPT, $options);

It's recommended that, not to use a static salt or one that is not randomly generated. For the VAST majority of use-cases, let password_hash() generate the salt randomly for you.

The password could be verified using the password_verify() function, for example :

if (password_verify('mypassword', $hash)) {
    echo 'Password is valid!';
}
else {
    echo 'Invalid password.';
}

Note that password_hash() returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.

Other two related functions are password_get_info($hashed_password), which returns an array of information about the hash that was created by an algorithm supported by password_hash() function and password_needs_rehash($hashed_password, $used_algorithm, $options), it checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed.

The list() construct is supported in foreach :

The foreach control structure now supports unpacking nested arrays into separate variables via the list() construct. For example:

$array = [
    [1, 2],
    [3, 4],
];
// Loop the Array using foreach
// while unpacking items using list
foreach ($array as list($a, $b)) {
    echo "A: $a; B: $b\n";
}
// Output :
/**
  * A: 1; B: 2
  * A: 3; B: 4
  */
support for arbitrary expressions in empty() function :

Passing an arbitrary expression instead of a variable to empty() is now supported. For example:

function always_false()
{
    return false;
}
// Pass function to empty
if (empty(always_false())) {
    echo "This will be printed.\n";
}
// Pass Boolean true to empty
if (empty(true)) {
    echo "This will not be printed.\n";
}
// Output :
/**
  * This will be printed.
  */
Support for array and string dereferencing :

Array and string literals can now be dereferenced directly to access individual elements and characters, for example :

// Array dereferencing example
echo 'Array dereferencing: ';
echo [1, 2, 3][0];
echo "\n";
// String dereferencing example
echo 'String dereferencing: ';
echo 'PHP'[0];
echo "\n";
// Output :
/**
  * Array dereferencing: 1
  * String dereferencing: P
  */
Class name resolution via ::class :

It is possible to use ClassName::class to get a fully qualified name of class ClassName. For example:

namespace App\Controllers;
class MyClass {
  // ...
}
// Get fully qualified name (with namespace)
echo MyClass::class;
// Output :
/**
  * App\Controllers\MyClass
  */
Now foreach supports non-scalar keys :

The Iterator::key function can currently return a value of any type, but the handling code in foreach and several other places only allows integer and string keys to be used. This limitation makes some use-cases unnecessarily complicated. From the SPL two examples are MultipleIterator and SplObjectStorage.

The MultipleIterator allows you to traverse several Iterators at the same time. It's ::current method returns an array of values and the ::key method returns an array of keys. But due to the foreach key type limitation the keys can not be directly fetched, for example :

// This is NOT possible prior to php 5.5.0
foreach ($it as $keys => $values) {
    // ...
}
 
// Instead you have to use
foreach ($it as $values) {
    $keys = $it->keys();
    // ...
}

SplObjectStorage is a map/set implementation for object keys. Here the issue is circumvented by returning the keys as values and requiring a manual look up on the values :

// This is NOT possible prior to php 5.5.0
foreach ($objectStore as $key => $value) {
    // ...
}
 
// Instead you have to use
foreach ($objectStore as $key) {
    $value = $objectStore[$key];
     // ...
}

But now foreach supports keys of any type. While non-scalar keys cannot occur in native PHP arrays, it is possible for Iterator::key() to return a value of any type, and this will now be handled correctly. Read more on ths RFC link.

Improvements to GD

Various improvements have been made to the GD extension, these include:

OPcache extension added

The Zend Optimiser+ opcode cache has been added to PHP as the new OPcache extension. OPcache improves PHP performance by storing precompiled script bytecode in shared memory, thereby removing the need for PHP to load and parse scripts on each request. See the installation instructions for more detail on enabling and using OPcache.

This extension is bundled with PHP 5.5.0 and later, and is » available in PECL for PHP versions 5.2, 5.3 and 5.4.

Apache 2.4 handler supported on Windows

The Apache 2.4 handler SAPI is now supported on Windows. You can read more about apache handler. Also, the handler(php5apache2_4.dll) for PHP 5.4, 5.3 and 5.2 are available at Apache Lounge. Read this if interested in Developing modules for the Apache HTTP Server 2.4.

incompatibilities too and code should be tested before switching PHP versions in production environments. For users upgrading from PHP 5.4, a migration guide is available detailing the changes between 5.4 and 5.5.0.

Changes that affect compatibility:
  • PHP logo GUIDs have been removed.
  • Windows XP and 2003 support dropped.
  • Case insensitivity is no longer locale specific. All case insensitive matching for function, class and constant names is now performed in a locale independent manner according to ASCII rules.

Latest Blog

0
Php

PHP – 8.0 Match Expression

In PHP 8.0 there is a new feature or I should say a new language construct (keyword) going to be introduced,  which has been implemented depending […]

0
Php

New Union Type in PHP – 8

A new RFC has been finished voting and accepted for PHP – 8. That is “Union Types”, which is an extension of PHP’s type system. […]