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

PHP 7: A Journey from PHP 5.3

PHP 7: A Journey from PHP 5.3

Taking a look at the changes implemented in PHP since version 5.3, we discuss why it is high time developers upgrade to the latest versions of PHP

Avatar for Andrew Millington

Andrew Millington

November 04, 2016

More Decks by Andrew Millington

Other Decks in Programming

Transcript

  1. PHP USAGE Version 3 - less than 0.1% Version 4

    - 1% Version 5 - 97.2% 5.0 - less than 0.1% 5.1 - 0.7% 5.2 - 9.9% 5.3 - 26.4% 5.4 - 25.9% 5.6 - 17.9% 5.7 - less than 0.1% Version 7 - 1.8%
  2. WHAT ABOUT VERSION 6? Started in 2005 - abandoned in

    2010 Most functionality implemented in PHP 5.3 or PHP 5.4 MariaDB jumped from v5.5 to v10.0
  3. WHAT'S NEW IN PHP 5.4? Released the 1st of March

    2012 Supported until 3rd of September 2015
  4. TRAITS! Mechanism for code reuse Can be thought of as

    snippets of classes Avoids needless inheritance
  5. TRAITS! <?php trait Hello { public function sayHello() { echo

    'Hello'; } } trait World { public function sayWorld() { echo 'World'; } } class MyHelloWorld { use Hello, World; public function sayExclamationMark() {
  6. SHORT ARRAY SYNTAX <?php // Old array notation (but still

    valid) $oldArray = array('John', 'Ringo', 'Paul', 'George'); $oldArray2 = array('Marvel' => 'Spider­man', 'DC' => 'Superman'); // New short array syntax $newArray = ['John', 'Ringo', 'Paul', 'George']; $newArray2 = ['Marvel' => 'Spider­man', 'DC' => 'Superman'];
  7. FUNCTION ARRAY DEREFERENCING <?php function fruit() { return ['a' =>

    'apple', 'b' => 'banana']; } $fruits = fruit(); echo $fruits['a']; // apple
  8. FUNCTION ARRAY DEFERENCING <?php function fruit() { return ['a' =>

    'apple', 'b' => 'banana']; } echo fruit()['a']; // apple
  9. CLOSURE: OBJECT EXTENSION <?php class Other { private $value =

    1; public function getClosure() { return function () { return $this­>value; }; }
  10. SHORT ECHO ALWAYS AVAILABLE Regardless of the short_open_tag php.ini option

    <­­ Old way ­­> <input name="name" value="<?php echo 'Dave'; ?>"> <­­ New way ­­> <input name="name" value="<?= 'Dave'; ?>">
  11. CLASS MEMBER ACCESS ON INSTANTIATION <?php // Old way $foo

    = new Foo(); echo $foo­>bar() // Hello World! // New way echo (new Foo)­>bar(); // Hello World!
  12. CLASS::{EXPR}() SYNTAX SUPPORTED <?php $method = 'method'; class Test {

    public function method() { echo 'Method'; } } $test = new Test(); $test­>method(); // Method $test­>$method(); // Method $test­>{'method'}(); // Method Test::method(); // Method Test::$method(); // Method
  13. OTHER ADDITIONS TO PHP 5.4 Binary number format added e.g.

    0b001001101 Improved parse error messages and improved incompatible argument warnings The session extension can now track the upload progress of files Added a built in CLI web server (single threaded) e.g. php -S localhost:8000
  14. WHAT IS DEPRECATED IN PHP 5.4? Register Globals removed Break

    and continue no longer accept variable arguments e.g. break 1 + foo() * $bar; Converting Array to String generates E_NOTICE. Result will still be "Array" Call-time pass by reference no longer allowed e.g. foo(&$bar) {} And many others...
  15. STILL WITH ME?! ON TO PHP 5.5 Released 20th of

    June 2013 Supported until the 21st of July 2016
  16. GENERATORS! Iteration made easy! <?php function xrange($start, $limit, $step =

    1) { for ($i = $start; $i <= $limit; $i += $step) { yield $i; } } echo 'Single digit odd numbers: '; foreach (xrange(1, 9, 2) as $number) { echo $number . ' '; } // Single digit odd numbers 1 3 5 7 9
  17. COROUTINES - THE GENERATOR SISTER <?php function logger($fileName) { $fileHandle

    = fopen($fileName, 'a'); while (true) { fwrite($fileHandle, yield . "\n"); } } $logger = logger(__DIR__ . '/log'); $logger­>send('Foo'); $logger­>send('Bar');
  18. FINALLY KEYWORD ADDED <?php try { $timesAttempted = $this­>getTimesAttempted(); executeComplicatedCode();

    } catch (Exception $e) { echo 'Caught exception: ' . $e­>getMessage(); } finally { // Increment times attempted $this­>setTimesExecuted($timesAttempted++); }
  19. NEW PASSWORD HASHING API() Uses the function password_hash() Two algorithms

    supported: PASSWORD_DEFAULT PASSWORD_BCRYPT Password default is designed to change over time. Recommended to store passwords as 255 characters long to account for change in length as PHP is made more secure.
  20. FOREACH NOW SUPPORTS LIST() <?php $array = [ [1, 2],

    [3, 4] ]; foreach ($array as list($a, $b)) { echo 'A: ' . $a . ' B: ' . $b; } // Echoes A: 1 B: 2 A: 3 B: 4
  21. EMPTY SUPPORTS ARBITRARY EXPRESSIONS <?php function always_false() { return false;

    } if (empty(always_false())) { echo 'Print this'; } // Echoes Print this
  22. ARRAY AND STRING LITERAL DEREFERENCING <?php echo 'Array dereferencing: ';

    echo [1, 2, 3][0]; echo "\n"; echo 'String dereferencing: '; echo 'PHP'[0]; echo "\n"; // Array dereferencing: 1 // String dereferencing: P
  23. CLASS NAME RESOLUTION VIA ::CLASS <?php namespace Name\Space; class ClassName

    {} echo ClassName::class; // Echoes Name\Space\ClassName
  24. WHAT IS DEPRECATED IN PHP 5.5? The MySQL extension. You

    must use MySQLi or preferably PDO preg_replace /e modifier. Must now use preg_replace_callback() Some internationalisation functions around timezones Some mcrypt functions
  25. STILL WITH ME?! ONWARDS TO PHP 5.6, OUR CURRENT HOME

    Released 28th of August 2014 Supported until the 31st of December 2018 (yay)! Active support dies the end of this year. Security fixes only from the 31st of December 2016 (boo)
  26. CONSTANT EXPRESSIONS From PHP 5.3, we could use the const

    keyword as well as define(). ...but it came with some caveats. const could only contain scalar data. Boolean Integer Float String
  27. CONSTANT EXPRESSIONS NOT ANY MORE... <?php const ONE = 1;

    const TWO = ONE * 2; class Three { public function addConsts($a = ONE + TWO) { return $a; } }
  28. VARIADIC FUNCTIONS <?php function variadic($bandName, ...$albums) { echo $bandName .

    ' have ' . count($albums) . ' album(s); } variadic('Oasis', 'Definitely Maybe', '(What's the Story) Morning Glory?' // Echoes Oasis have 3 albums And if anyone contradicts that they are lying
  29. ARUGMENT UNPACKING <?php function add($a, $b, $c) { returns $a

    + $b + $c; } $operators = [2, 3]; echo add(1, ...$operators); // Echoes 6
  30. EXPONENTIATION VIA ** Must be right evaluated <?php printf("%d", 2

    ** 3); echo '<br>'; printf("%d", 2 ** 3 ** 2); // 8 // 512
  31. USE FUNCTION AND USE CONST Similar to importing classes you

    can now do the following <?php namespace Name\Space { const FOO = 42; function f() { echo __FUNCTION__ . "\n"; } } namespace { use const Name\Space\FOO; use function Name\Space\f; echo FOO . "\n"; f(); }
  32. OTHER ADDITIONS TO PHP 5.6 PHPdbg - the interactive PHP

    debugger default_charset used for htmlentities(), html_entity_decode() and htmlspecialchars() - Currently UTF-8 php://input can now be read multiple times File uploads larger than 2gb now accepted Magic method __debugInfo() allows you to modify object property and values when the object is output using var_dump() And many others...
  33. FINALLY, PHP 7. THE HOLY GRAIL. WHAT'S NEW? Released 3rd

    of December 2016 Support ends 3rd of December 2018... before PHP 5.6
  34. LONG OVERDUE SCALAR TYPES RFC by University of Aberdeen's very

    own Andrea Faulds I checked and she has used MyTimetable... (cringe) Scalar type declarations come in two flavours: strict and coercive (default) Support strings, integers, floats and bools
  35. LONG OVERDUE SCALAR TYPES <?php // Coercive mode function sumOfInts(int

    ...$ints) { return array_sum($ints); } var_dump(sumOfInts(2, '3', 4.1)); // Will return int(9)
  36. RETURN TYPE DECLARATIONS <?php function sum($a, $b): float { return

    $a + $b; } var_dump(sum(1, 2)); // Returns float(3)
  37. NULL COALESCING OPERATOR Avoids having to use a ternary operator

    in conjunction with isset() <?php $username = $_GET['user'] ?? 'nobody';
  38. SPACESHIP OPERATOR Also proposed by Andrea Faulds <?php // Integers

    echo 1 <=> 1; // 0 echo 1 <=> 2; // ­1 echo 2 <=> 1; // 1
  39. ANONYMOUS CLASSES Can be used in place of full class

    definitions for throwaway objects <?php function anonymous_class() { return new class {}; } if (get_class(anonymous_class()) === get_class(anonymous_class())) { echo 'same class'; } else { echo 'different class'; } // Echoes same class
  40. GROUP USE DECLARATIONS <?php // Pre PHP 7 Code use

    some\namespace\ClassA; use some\namespace\ClassB; use some\namespace\ClassC; // PHP 7 Code use some\namespace\{ClassA, ClassB, ClassC}
  41. GENERATOR RETURN EXPRESSIONS <?php $gen = (function () { yield

    1; yield 2; return 3; })(); foreach ($gen as $val) { echo $val, PHP_EOL; } echo $gen­>getReturn(), PHP_EOL;
  42. Delegate yield to another generator, Traversable or Array automatically GENERATOR

    DELEGATION <?php function gen() { yield 1; yield 2; yield from gen2(); } function gen2() { yield 3; yield 4; } foreach($gen as $val) { echo $val . ' '; } // 1 2 3 4 And many, many other additions...
  43. WHAT'S DEPRECATED IN PHP 7? PHP 4 style constructors. Must

    use __constructor() instead Static calls to non-static methods no longer allowed. Not sure why they were originally... password_hash() no longer accepts salts. It generates its own salt ldap_sort() deprecated
  44. HOW FAST IS PHP7? MAGENTO PERFORMANCE x2 execution time, 30%

    lower memory, 3x the requests of PHP 5.6