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)

Ca57a7cfac69ba3abf517470f3770aae?s=128

Jeremy Lindblom

January 26, 2016
Tweet

Transcript

  1. new features in php7 By Jeremy Lindblom @jeremeamia McGraw-Hill Education

  2. @jeremeamia

  3. today: 1. brief history 2.what’s new? 3.what changed?

  4. did you know... php7 is compatible with star wars &

    star trek fans?
  5. new features or maybe... an awakening of new powers? php7

    a.k.a. PHP VII
  6. PHP VII: The PHorce Awakens

  7. PHP7 is based on a new version or the “next

    generation” of the Zend Engine, called: phpng
  8. PHP: The Next Generation

  9. a brief history of php part one

  10. Once upon a time…

  11. 1995: PHP is born

  12. 1998: PHP 3 & The ElePHPant

  13. 2000: PHP 4 & Zend Engine

  14. 2003: ???

  15. 2003: Jeremy Graduates

  16. 2003: WordPress

  17. 2004: PHP 5 & OOP

  18. 2006: AWS & The Cloud

  19. 2007: PHP 5.2 & Frameworks

  20. 2009: PHP 5.3 is released

  21. 2010: ♥ for Git/GitHub grows

  22. 2011: Composer & PSR-0

  23. 2013: Laravel, hhvm, & PHP 5.5

  24. 2015: PHP7 & 20th Birthday

  25. 2016: PHP 7.1 & Beyond

  26. what’s new in php7? part two

  27. But first...

  28. 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 ( ** )
  29. None
  30. It’s faster!

  31. Like, waaay faster!!!

  32. Benchmark: Wordpress 4.1

  33. Benchmark: Wordpress 4.1

  34. None
  35. ➡ Twice as fast ➡ Half the memory

  36. Your Server Cluster

  37. Your Server Cluster

  38. ➡ Twice as fast ➡ Half the memory ∴ Lower

    Costs
  39. None
  40. Scalar Type Hints

  41. 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) { … }
  42. 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) { … }
  43. Coercive vs. Strict // Given the following function: function sum(int

    ...$numbers) { return array_sum($numbers); } echo sum(3, 1, 7); //> 11
  44. Coercive vs. Strict (cont.) declare(strict_types=0); // coercive mode echo sum(4,

    2); //> 6 echo sum(4.1, 2.1); //> 6
  45. Coercive vs. Strict (cont.) declare(strict_types=1); // strict mode echo sum(4,

    2); //> 6 echo sum(4.1, 2.1); //> TypeError
  46. [PHP 7.1] Nullable Type Hints function prefix(?string $prefix, string $str)

    { … }
  47. Return Type Declarations

  48. Works with functions, methods, and closures function sum(int ...$numbers): int

    { … } $fn = function (int $num) use ($max): int { … }
  49. [PHP 7.1] Void Return Types function execute(Command $cmd): void {

    … }
  50. Null Coalescing Operator

  51. 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;
  52. 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;
  53. Null Coalescing Operator (Added in PHP 7) // Ternary with

    set variable $result = $value ?: $default; // Null coalescing with non-set variable $result = $value ?? $default;
  54. Anonymous Classes

  55. 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"; } };
  56. 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+'); } };
  57. 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
  58. Group use Declarations

  59. 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"; } };
  60. 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;
  61. 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};
  62. Spaceship Operator <=> <=>

  63. 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)
  64. Spaceship in Action usort($people, function ($person1, $person2) { return $person1->age

    <=> $person2->age; });
  65. CSPRNG Functions

  66. CSPRNG Functions Cryptographically Secure Pseudo– Random Number Generator random_int($min, $max):

    int random_bytes($length): string
  67. Symmetric Array Destructuring PHP 7.1

  68. [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;
  69. Class Constant Visibility PHP 7.1

  70. [PHP 7.1] Class Constant Visibility class ConstDemo { public const

    PUBLIC_CONST_B = 1; protected const PROTECTED_CONST = 2; private const PRIVATE_CONST = 4; }
  71. 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
  72. what has been changed? part three

  73. i.e., what has been broken ? part three

  74. Throwing New Things

  75. Exception RuntimeException LogicException PHP 5 Exception Hierarchy

  76. Error TypeError ParseError ArithmeticError PHP 7 Error Hierarchy

  77. Error TypeError ParseError ArithmeticError PHP 7 Throwable Top-Level Interface Throwable

    Exception RuntimeException LogicException
  78. 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
  79. More Consistent Syntax

  80. 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 ( )
  81. Uniform Variable Syntax – Examples

  82. Forbid Dynamic Scope Funcs PHP 7.1

  83. [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()
  84. Not All Extensions Available

  85. GoPHP7-ext http://gophp7.org/gophp7-ext/

  86. Removed the Rubbish

  87. 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) { … }
  88. 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)
  89. more resources appendix

  90. 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
  91. Migration Guide http://php.net/manual/en/migration70.php

  92. Thanks! By Jeremy Lindblom @jeremeamia McGraw-Hill Education