$30 off During Our Annual Pro Sale. View Details »

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
Tweet

More Decks by Jeremy Lindblom

Other Decks in Programming

Transcript

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

    View Slide

  2. @jeremeamia

    View Slide

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

    View Slide

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

    View Slide

  5. new features
    or maybe...
    an awakening of new powers?
    php7
    a.k.a.
    PHP VII

    View Slide

  6. PHP VII: The PHorce Awakens

    View Slide

  7. PHP7 is based on a new version
    or the
    “next generation”
    of the
    Zend Engine, called:
    phpng

    View Slide

  8. PHP: The Next Generation

    View Slide

  9. a brief
    history of php
    part one

    View Slide

  10. Once upon a time…

    View Slide

  11. 1995: PHP is born

    View Slide

  12. 1998: PHP 3 & The ElePHPant

    View Slide

  13. 2000: PHP 4 & Zend Engine

    View Slide

  14. 2003: ???

    View Slide

  15. 2003: Jeremy Graduates

    View Slide

  16. 2003: WordPress

    View Slide

  17. 2004: PHP 5 & OOP

    View Slide

  18. 2006: AWS & The Cloud

    View Slide

  19. 2007: PHP 5.2 & Frameworks

    View Slide

  20. 2009: PHP 5.3 is released

    View Slide

  21. 2010: ♥ for Git/GitHub grows

    View Slide

  22. 2011: Composer & PSR-0

    View Slide

  23. 2013: Laravel, hhvm, & PHP 5.5

    View Slide

  24. 2015: PHP7 & 20th Birthday

    View Slide

  25. 2016: PHP 7.1 & Beyond

    View Slide

  26. what’s new
    in php7?
    part two

    View Slide

  27. But first...

    View Slide

  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 ( ** )

    View Slide

  29. View Slide

  30. It’s faster!

    View Slide

  31. Like, waaay faster!!!

    View Slide

  32. Benchmark: Wordpress 4.1

    View Slide

  33. Benchmark: Wordpress 4.1

    View Slide

  34. View Slide

  35. ➡ Twice as fast
    ➡ Half the memory

    View Slide

  36. Your Server Cluster

    View Slide

  37. Your Server Cluster

    View Slide

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

    View Slide

  39. View Slide

  40. Scalar Type Hints

    View Slide

  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) { … }

    View Slide

  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) { … }

    View Slide

  43. Coercive vs. Strict
    // Given the following function:
    function sum(int ...$numbers) {
    return array_sum($numbers);
    }
    echo sum(3, 1, 7); //> 11

    View Slide

  44. Coercive vs. Strict (cont.)
    declare(strict_types=0);
    // coercive mode
    echo sum(4, 2); //> 6
    echo sum(4.1, 2.1); //> 6

    View Slide

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

    View Slide

  46. [PHP 7.1] Nullable Type Hints
    function prefix(?string $prefix, string $str) { … }

    View Slide

  47. Return Type Declarations

    View Slide

  48. Works with functions, methods, and closures
    function sum(int ...$numbers): int { … }
    $fn = function (int $num) use ($max): int { … }

    View Slide

  49. [PHP 7.1] Void Return Types
    function execute(Command $cmd): void { … }

    View Slide

  50. Null Coalescing Operator

    View Slide

  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;

    View Slide

  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;

    View Slide

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

    View Slide

  54. Anonymous Classes

    View Slide

  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";
    }
    };

    View Slide

  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+');
    }
    };

    View Slide

  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

    View Slide

  58. Group use Declarations

    View Slide

  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";
    }
    };

    View Slide

  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;

    View Slide

  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};

    View Slide

  62. Spaceship Operator
    <=>
    <=>

    View Slide

  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)

    View Slide

  64. Spaceship in Action
    usort($people, function ($person1, $person2) {
    return $person1->age <=> $person2->age;
    });

    View Slide

  65. CSPRNG Functions

    View Slide

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

    View Slide

  67. Symmetric Array Destructuring
    PHP
    7.1

    View Slide

  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;

    View Slide

  69. Class Constant Visibility
    PHP
    7.1

    View Slide

  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;
    }

    View Slide

  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

    View Slide

  72. what has been
    changed?
    part three

    View Slide

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

    View Slide

  74. Throwing New Things

    View Slide

  75. Exception
    RuntimeException LogicException
    PHP 5 Exception Hierarchy

    View Slide

  76. Error
    TypeError ParseError
    ArithmeticError
    PHP 7 Error Hierarchy

    View Slide

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

    View Slide

  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

    View Slide

  79. More Consistent Syntax

    View Slide

  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 ( )

    View Slide

  81. Uniform Variable Syntax – Examples

    View Slide

  82. Forbid Dynamic Scope Funcs
    PHP
    7.1

    View Slide

  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()

    View Slide

  84. Not All Extensions Available

    View Slide

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

    View Slide

  86. Removed the Rubbish

    View Slide

  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) { … }

    View Slide

  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 )<br/>● Can no longer have multiple default blocks in a switch<br/>(They were ignored before, now they cause an error)<br/>

    View Slide

  89. more
    resources
    appendix

    View Slide

  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

    View Slide

  91. Migration Guide
    http://php.net/manual/en/migration70.php

    View Slide

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

    View Slide