Home » Releases » PHP 5.5 »

PHP 5.5 Code Comparisons

Explore PHP 5.5

Generators

PHP 5.5 introduces generators, providing an easy way to make iterators without the overhead or complexity of implementing the Iterator interface. A function with yield returns a generator object.
Before PHP 5.5
class LineReader implements Iterator
{
    // Complex iterator boilerplate...
}
PHP 5.5 or Later
function getLines(string $file)
{
    $handle = fopen($file, 'r');
    while (($line = fgets($handle))
        !== false
    ) {
        yield $line;
    }
    fclose($handle);
}

Try/Catch/Finally

PHP 5.5 adds native support for try-catch-finally blocks. The code inside the finally block is always executed after try and catch blocks, regardless of whether an exception was thrown.
Before PHP 5.5
$conn = connect();
try {
    doWork($conn);
    disconnect($conn);
} catch (Exception $e) {
    disconnect($conn);
    throw $e;
}
PHP 5.5 or Later
$conn = connect();
try {
    doWork($conn);
} finally {
    disconnect($conn);
}

Class Name Resolution via ::class

PHP 5.5 introduces the ::class syntax for class name resolution. This allows obtaining the fully qualified name (FQN) of a class, interface, or trait safely at compile time without relying on __CLASS__ or get_class().
Before PHP 5.5
$name = 'App\\Entity\\User';
$container->get($name);
PHP 5.5 or Later
$name = User::class;
$container->get($name);

Expressions in empty()

Prior to PHP 5.5, passing function return values or expressions to empty() resulted in a fatal error. PHP 5.5 allows any expression inside empty().
Before PHP 5.5
$result = trim($input);
$isEmpty = empty($result);
PHP 5.5 or Later
$isEmpty = empty(trim($input));