New features of PHP 5.5

This entry is part 1 of 3 in the series: PHP new features

PHP
In recent years the PHP community has made a great effort to improving and adding new features and functionality to this popular programming language in order to make it more attractive, functional and useful. With the release of PHP 5.5 have been introduced some features very expected by the developer community. Today LibreByte proposes to show everything new which brings PHP 5.5.

– Generators: Generators provide an easy way to build simple iterators without to implement the Iterator interface but with the drawback that not can be rewind (return the pointer to the first element) after the iteration has been started. The master piece of generators is the keyword yield, which in its simple form resembles the statement return but instead of aborting the execution of the function and return a value keeps the value of the variable and pause while function is iterated on the generator. To get an idea of how it works here an example:

function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i < = $limit; $i += $step) {
        print_r("Generated value: $i");
        yield $i;
    }
}

foreach(xrange(0, 3) as $num) {
    print_r("Processing num: $num n");
}

// Output
// Generated value: 0
// Processing num: 0
// Generated value: 1
// Processing num: 1
// Generated value: 2
// Processing num: 2
// Generated value: 3
// Processing num: 3

- Keyword finally: now the block try {...} catch () {...} supports finally enabling execute php statements regardless of whether it occurred or not an exception, example:

class InvalidDateException extends Exception {}

function test_finally() {
    try {
        print_r("Try to create a DateTime object");
        new DateTime('oooooooh!');
    } catch (Exception $e) {
        print_r ("Error creating the DateTime object");
        throw new InvalidDateException();
    } finally {
        print_r ("finally cleaning tasks");
    }
}

try {
    test_finally();
} catch (InvalidDateException $e) {;
    print_r ("Capture my own exception (InvalidDateException)");
}

// Output
// Try to create a DateTime object
// Error creating the DateTime object
// finally cleaning tasks
// Capture my own exception (InvalidDateException)

– New API for encryption of password that provides a robust and one-way encryption algorithm. Reference: password_hash, password_get_info, password_needs_rehash, password_verify

– Now the foreach control structure allows unpacking nested arrays using the list statement, example:


$array = [
[1, 2],
[3, 4],
];

foreach ($array as list($a, $b)) {
    echo "A: $a; B: $bn";
}


// The result of the example would be:
// A: 1; B: 2
// A: 3; B: 4

// Also you can use key => value

$array = [
    'ID1' => [1, 2],
    'ID2' => [3, 4],
];

foreach ($array as $key => list($a, $b)) {
    echo "Key: $key, A: $a; B: $bn";
}

// The result would be
// Llave: ID1, A: 1; B: 2
// Llave: ID2, A: 3; B: 4

– Now empty funciton supports arbitrary expressions, examples

Before PHP 5.5 the following sentences generates a syntax error

empty([]);
empty("aaa");
empty(true);
empty(0);

After PHP 5.5 previous statements are valid, also the function empty supports function calls:

Class Test
{
    public static function isEmpty()
    {
        return false;
    }
}

function is_empty() {
    return 'is not empty';
}


var_dump(empty(Test::isEmpty()));
var_dump(empty(is_empty()));

// Output
// bool(true)
// bool(false

– PHP 5.5 allows you to dereference array and string literals (from PHP 5.4 is also possible to dereference array returned by functions)

print_r(['A', 'B', 'C'][0] . "n");
print_r('ABCD'[0] . "n");

// Output
// A
// A

– PHP 5.5 allows you to obtain the full name of a class, including the namespace to which it belongs, by using the static property: class

namespace My\Namespace;

class MyClass {}

echo MyClass::class, "\n";

// Output
// My\Namespace\MyClass

– The Zend Optimiser +opcode cache has been added as a new extension (OPcache). OPcache improves the performance of your applications storing precompiled php code and avoiding the interpretation of php scripts in each request.

– PHP 5.5 introduces several improvements to the GD extension

-Introduces the function array_column which allows you to obtain all the values associated with a column of an array of array, for example start that we have the following information in a database (subset of the actor table of the DB sakila)

+----------+------------+--------------+---------------------+
| actor_id | first_name | last_name    | last_update         |
+----------+------------+--------------+---------------------+
|        1 | PENELOPE   | GUINESS      | 2006-02-15 04:34:33 |
|        2 | NICK       | WAHLBERG     | 2006-02-15 04:34:33 |
|        3 | ED         | CHASE        | 2006-02-15 04:34:33 |
|        4 | JENNIFER   | DAVIS        | 2006-02-15 04:34:33 |
|        5 | JOHNNY     | LOLLOBRIGIDA | 2006-02-15 04:34:33 |
+----------+------------+--------------+---------------------+

and we run the following PHP statements

$sql = 'SELECT * FROM actor LIMIT 5';

if ($link = mysqli_connect('localhost', 'root', 'root', 'sakila')) {
    if ($result = mysqli_query($link, $sql)) {
        $actors = mysqli_fetch_all($result, MYSQLI_ASSOC);
        print_r(array_column($actors, 'first_name', 'actor_id'));
    }
}

the result would be as follows

Array
(
[1] => PENELOPE
[2] => NICK
[3] => ED
[4] => JENNIFER
[5] => JOHNNY
)

-The mysql extension became obsolete and is instead recommended to use mysqli or PDO

Further reading

Migrate from PHP 5.4.x to PHP 5.5.x




Leave a Comment

Your email address will not be published. Required fields are marked *