Upgrade to Pro — share decks privately, control downloads, hide ads and more …

New Features in PHP 7

New Features in PHP 7

PHP7 is the first major version of PHP to be released since 2004, and has brought us dozens of new features and huge performance gains. Let's take a tour of the latest and greatest PHP has to offer, and also see if it is safe for you to update your servers. (First given in January 2016 to the @azPHP user group. Updated with information about PHP 7.1 in October 2016 for Desert Code Camp)

Jeremy Lindblom

January 26, 2016

Transcript

92 slides
  1. PHP7 is based on a new version or the “next

    generation” of the Zend Engine, called: phpng
  2. New Features in PHP 5 Since Version 5.2 Namespaces &

    Class Imports Late Static Binding Closures goto Ternary Shortcut ( ?: ) Traits Short Array Syntax ( [ ] ) Built-in Server Generators password_hash() API finally Variadic Functions ( ... ) Function/Const Imports Exponentiation Operator ( ** )
  3. Type hints in PHP 5 // “array”, “callable”, “self”, and

    class names allowed function getPeople(array $ids) { … } function delete($id, callable $onFailure) { … } function hire(Person $person) { … }
  4. Type declarations in PHP 7 (a.k.a. scalar type hints) //

    “int”, “float”, “string”, and “bool” now allowed function truncate(string $str, int $length) { … } function coord(float $x, float $y) { … }
  5. Coercive vs. Strict // Given the following function: function sum(int

    ...$numbers) { return array_sum($numbers); } echo sum(3, 1, 7); //> 11
  6. Works with functions, methods, and closures function sum(int ...$numbers): int

    { … } $fn = function (int $num) use ($max): int { … }
  7. Ternary Statements in PHP 5 // Ternary with set variable

    $result = !empty($value) ? $value : $default; // Null coalescing with non-set variable $result = isset($value) ? $value : $default;
  8. Ternary Shortcut Syntax (Added in PHP 5.3) // Ternary with

    set variable $result = $value ?: $default; // Null coalescing with non-set variable $result = isset($value) ? $value : $default;
  9. Null Coalescing Operator (Added in PHP 7) // Ternary with

    set variable $result = $value ?: $default; // Null coalescing with non-set variable $result = $value ?? $default;
  10. Anonymous Classes use Psr\Log\{LoggerInterface, LoggerTrait}; $log = new class() implements

    LoggerInterface { use LoggerTrait; public function log($lvl, $msg, array $ctx = []) { echo $lvl . ': ' . strtr($msg, $ctx) . "\n"; } };
  11. Anonymous Classes and Constructors $log = new class(string $path) implements

    LoggerInterface { use LoggerTrait; private $file; public function __construct(string $path) { $this->file = fopen($path, 'w+'); } };
  12. Anonymous Classes Tips • function is to closure as class

    is to anonymous class • Works the same as a regular class, but without a name • May be helpful for implementing... ◦ internal, private, or undocumented classes ◦ single-use objects ◦ implementing small interfaces • Cannot be serialized
  13. Group use Declarations use Psr\Log\{LoggerInterface, LoggerTrait}; $log = new class()

    implements LoggerInterface { use LoggerTrait; public function log($lvl, $msg, array $ctx = []) { echo $lvl . ': ' . strtr($msg, $ctx) . "\n"; } };
  14. More Examples – PHP 5 use My\App\ClassA; use My\App\ClassB as

    B; use function My\App\function_a; use function My\App\function_b; use const My\App\CONSTANT_A; use const My\App\CONSTANT_B;
  15. More Examples – PHP 7 use My\App\{ClassA, ClassB as B};

    use function My\App\{function_a, function_b}; use const My\App\{CONSTANT_A, CONSTANT_B};
  16. Combined Comparison (“Spaceship”) Operator • Looks like a UFO: $a

    <=> $b • Like strcmp() but for numbers, other scalars, and arrays • Returns -1, 0, or 1, which is perfect for sorting • Same logic can be accomplished for numbers by doing: ($a < $b) ? -1 : (($a > $b) ? 1 : 0)
  17. [PHP 7.1] Symmetric Array Destructuring // Destructuring in PHP 5

    list($class, $method) = explode('::', $name); // Say goodbye to list() in PHP 7 [$class, $method] = explode('::', $name); // Can also destructure arrays with non-integer keys ['id' => $id, 'name' => $name] = $data;
  18. [PHP 7.1] Class Constant Visibility class ConstDemo { public const

    PUBLIC_CONST_B = 1; protected const PROTECTED_CONST = 2; private const PRIVATE_CONST = 4; }
  19. Generator Return Expressions Generator Delegation ( yield from ) ReflectionGenerator

    Class Unicode Escape Syntax IntlChar Class Filtered unserialize() Multi-catch Exception Handling iterable pseudo-type Expectations via assert() intdiv() Function New session_start() Options Constant Arrays via define() Closure::call() Method Multi-level dirname() w/ New Arg Negative string offsets ( $str[-2]) Closure::fromCallable() Method Additional New Features in PHP 7.x 7.1
  20. Exceptions, Errors, and Throwables • Fatal errors are now a

    type of exception, or Throwable • To catch anything, catch Throwable • Be careful with functions type hinting for Exception, because they may end up receiving a Throwable instead • Parsing errors when using eval() now throw ParseError • Dividing by zero now throws a DivisionByZeroError
  21. Uniform Variable Syntax • PHP uses an AST under-the-hood now

    • Better consistency at the cost of minor backward-incompatibility issues • Handling of variables/functions is left-to-right always • When in doubt, add { } or ( )
  22. [PHP 7.1] Forbid Dynamic Scope Functions Can no longer dynamically

    call the following functions: assert() compact() extract() func_get_args() func_get_arg() func_num_args() get_defined_vars() mb_parse_str() parse_str()
  23. Removed and/or Deprecated • mysql, mssql, and ereg extensions are

    gone (Use mysqli/pdo, and pcre like you’ve already been doing) • PHP 4 style constructors deprecated class Foo { function Foo($bar) { … } } • Can no longer assign-by-reference with new $foo =& new Foo(); • Can no longer repeat parameter names function foo($fizz, $_, $_, $buzz) { … }
  24. Removed and/or Deprecated (cont.) • Static calls to non-static methods

    deprecated class Foo { function bar() { … } } Foo::bar(); • No more E_STRICT errors. • No more alternative PHP tags ( <%, <%=, or <script language="php"> ) • Can no longer have multiple default blocks in a switch (They were ignored before, now they cause an error)
  25. Upgrading to PHP 7 • Upgrade to PHP 5.6, if

    you aren’t there yet • Review the migration guides and your code • For libraries, use travis-ci.org to run your tests on PHP 7 • Use 3v4l.org to try out code snippets • Use “The Cloud”, Docker, and/or Vagrant for testing • Homebrew has PHP 7

More Decks by Jeremy Lindblom

Other Decks in Programming