Skip to content

Instantly share code, notes, and snippets.

@grebaldi
Last active November 2, 2016 03:00
Show Gist options
  • Save grebaldi/2f6574f50bfa30b87e87 to your computer and use it in GitHub Desktop.
Save grebaldi/2f6574f50bfa30b87e87 to your computer and use it in GitHub Desktop.
PHP 7 Features

PHP 7

Features you might not have known in 5.4, 5.5, 5.6

5.4

  • Traits
  • Short array syntax
  • $this in closures

5.5

  • Generators (function ($x) { while ($x > 0) yield $x--; })
  • finally
  • list() support for foreach
  • array and string literal dereferencing ([23,42,1138][0])
  • ::class

5.6

  • Variadic functions (rest operator ...$params)
  • Spread operator (...$params in a function call)
  • use function and use const
  • http://phpdbg.com/docs

Major features in 7

Scalar type declarations

function doSomething(int $number)
{
    return $number * $number;
}

Return type declarations

function doSomething() : array
{
    return [1, 2, 3];
}

Anonymous classes

class MyAwesomeClass {

    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

}

$awesomeInstance = new MyAwesomeClass();
$awesomeInstance->setLogger(new class implements LoggerInterface {

    public function log($message)
    {
        file_put_contents('log.txt', $message);
    }

});

Minor features in 7

  • Null coalescing operator $a ?? $b (if $a is null, return $b)
  • Spaceship operator $a <=> $b (sorting comparison)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment