What is new in PHP 5.5?

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:

<?php
function xrange($start, $limit, $step = 1) {
    for ($i = $start; $i < = $limit; $i += $step) {
        print_r("Valor generado: $i");
        yield $i;
    }
}

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

// Salida
// Valor generado: 0
// Procesando num: 0 
// Valor generado: 1
// Procesando num: 1 
// Valor generado: 2
// Procesando num: 2 
// Valor generado: 3
// Procesando 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:

<?php
class InvalidDateException extends Exception {}

function test_finally() {
	try {
		print_r("Intento crear un objeto DateTime");
		new DateTime('oooooooh!');
	} catch (Exception $e) {
		print_r("Error creando el objeto DateTime");
		throw new InvalidDateException(); 
	} finally {
		print_r("Finalmente tareas de limpieza");
	}
}

try {
    test_finally();
} catch (InvalidDateException $e) {;
	print_r("Capture mi propia excepción (InvalidDateException)n");
}

// Salida
// Intento crear un objeto DateTime
// Error creando el objeto DateTime
// Finalmente tareas de limpieza 
// Capture mi propia excepción (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:

<?php
$array = [
    [1, 2],
    [3, 4],
];
 
foreach ($array as list($a, $b)) {
    echo "A: $a; B: $bn";
}

 
// El resultado del ejemplo sería:
// A: 1; B: 2
// A: 3; B: 4

// Tambien puedes usar llaves valor

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

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

// El resultado sería
// Llave: ID1, A: 1; B: 2
// Llave: ID2, A: 3; B: 4

Now empty function supports arbitrary expressions, examples

Before PHP 5.5 the following sentences generates a syntax error

<?php
empty([]);
empty("aaa");
empty(true);
empty(0);

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

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

function is_empty() {
	return 'no es empty';
}


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

// Salida
// bool(true)
// bool(false

PHP 5.5 allows you to des-reference array and string literals (from PHP 5.4 is also possible to deference array returned by functions)

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

// Salida
// 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

<?php
namespace Mi\Espacio\De\Nombre;

class MiClase {}

echo MiClase::class, "\n";

// Salida
//Mi\Espacio\De\Nombre\MiClase

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

<?php
$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

YouTube video

Further reading

YouTube video

PHP new features, 6 (8)

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.