New Wave PHP

D33d8bdd9096c80b8d1acca8d28410b5?s=47 Lorna Mitchell
February 15, 2015

New Wave PHP

Features arriving in the most recent versions of PHP, along with gotchas and advice for upgrading your existing platforms.

D33d8bdd9096c80b8d1acca8d28410b5?s=128

Lorna Mitchell

February 15, 2015
Tweet

Transcript

  1. 1.

    New Wave PHP Lorna Mitchell, PHPUK 2015 (these slides are

    already online http://lrnja.net/new-wave-php)
  2. 5.

    Register Globals is Gone (5.4) Upgrade PHP and see many

    undefined (simple) variables. To fix each undefined variable: •replace $username with $_GET['username'] or $_POST['username'] in each case
  3. 6.

    Echo Shortcut (5.4) PHP 5.4 removes short_open_tag config option •<?

    is never valid - s/<?/<?php/ •<?= is always valid <?= is the same as: <?php echo
  4. 7.

    Error Reporting: E_STRICT E_ALL includes E_STRICT in PHP 5.4+ You

    can either: 1.Fix your errors 2.Turn it off again using E_ALL & ~E_STRICT
  5. 8.

    Timezone Settings (5.4) PHP refuses to guess the timezone and

    will warn you. It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. Fix it by setting date.timezone in php.ini: date.timezone = "Europe/London"
  6. 9.

    Call Time Pass By Reference PHP Fatal error: Call-time pass-by-reference

    has been removed This error says "don't pass references in when the function didn't expect them, you fool"
  7. 10.

    Call Time Pass By Reference You can pass by reference.

    Declare function: 1 function inspire(&$person) { 2 // be inspiring 3 } Call with just $ and not & 1 inspire($current_user);
  8. 11.

    Traits (5.4) Traits are building blocks for classes Traits can:

    •build on one another •be used together •are inherited by child classes
  9. 12.

    Traits 1 namespace Silex\Application; 2 use Monolog\Logger; 3 4 trait

    MonologTrait { 5 public function log($message, $context = array(), $level) { 6 return $this['monolog']->addRecord( 7 $level, $message, $context); 8 } 9 }
  10. 13.

    Traits To use a trait: 1 use Silex\Application; 2 class

    MyApplication extends Application { 3 use Application\MonologTrait; 4 5 public function myAwesomeMethod() { 6 ... 7 $this->log("Something happened"); 8 ...
  11. 14.

    DateTimeImmutable (5.5) DateTime is awesome 1 $important_date = new DateTime();

    2 print_r($important_date); 3 $result = $important_date->add(new DateInterval('P4D')); 4 print_r($important_date); 5 print_r($result); DateTime Object ( [date] => 2015-02-14 20:28:20 ... ) DateTime Object ( [date] => 2015-02-18 20:28:20 ... ) DateTime Object ( [date] => 2015-02-18 20:28:20 ... )
  12. 15.

    DateTimeImmutable DateTimeImmutable does what you'd expect 1 $important_date = new

    DateTimeImmutable(); 2 print_r($important_date); 3 $result = $important_date->add(new DateInterval('P4D')); 4 print_r($important_date); 5 print_r($result); DateTime Object ( [date] => 2015-02-14 20:28:20 ... ) DateTime Object ( [date] => 2015-02-14 20:28:20 ... ) DateTime Object ( [date] => 2015-02-18 20:28:20 ... )
  13. 16.

    Easy Password Hashing (5.5) Strongly hash your passwords with a

    built-in salt. Please? 1 $pass = "secretpassword"; 2 $hashed = password_hash($pass, PASSWORD_DEFAULT); 3 echo $hashed; Output: $2y$10$Q7Rm.Cmcu4lbvI7.C2q4Z.1LLoh4C63vBSfflQtfjs52GxhAc.s/G (make your password columns wider! 255 chars recommended)
  14. 17.

    Easy Password Hashing 1 $existing_hash = '$2y$10$Q7Rm.Cmcu4lbvI7.C2q4Z.1LLoh4C63vBSfflQt 2 $pass =

    "secretpassword"; 3 4 if(password_verify($pass, $existing_hash)) 5 echo "All good"; 6 else 7 echo "Go away"; For PHP < 5.5: http://github.com/ircmaxell/password_compat
  15. 19.

    Generators 1 function readLogsFromDatabase() { 2 $db = new PDO('mysql:host=localhost;dbname=test',

    $user, $p 3 $stmt = $db->query("select message from logs"); 4 while ($row = $stmt->fetch()) { 5 yield $row['message']; 6 } 7 } 8 9 foreach (readLogsFromDatabase() as $msg) { 10 echo $msg."\n"; 11 }
  16. 21.

    Coroutines 1 function dbLogWriter() { 2 $db = new PDO('mysql:host=localhost;dbname=test');

    3 $stmt = $db->prepare( 4 "insert into logs (message) values (:msg);"); 5 while (true) { 6 $msg = yield; 7 $stmt->execute(array("msg" => $msg)); 8 } 9 }
  17. 23.

    MySQL Extension is Deprecated (5.5) The original mysql extension now

    emits E_DEPRECATED warnings. Instead, use: •PDO - excellent OO database handling •The mysqli extension, quite similar to the original mysql one
  18. 24.

    Built-in OpCache (5.5) Replaces APC - be aware that OpCache

    is disabled by default. Turn on opcache.enable and opcache.enable_cli
  19. 25.

    DebugInfo (5.6) Magic method __debugInfo() to change what is given

    to var_dump() 1 class MyBuggyClass { 2 public function __debugInfo() { 3 return $this->problemData; 4 } 5 } 6 7 ... 8 var_dump(new MyBuggyClass()); // custom output
  20. 26.

    Variadic Functions (5.6) 1 function combine($transform, ...$strings) { 2 $string

    = ''; 3 4 foreach($strings as $piece) { 5 $string .= $piece; 6 } 7 return($transform($string)); 8 } 9 10 echo combine("strtoupper", "I'd ", "like ", 4 + 2, " apples"); 11 // I'D LIKE 6 APPLES
  21. 27.

    Argument Unpacking (5.6) Let PHP unpack your function parameters 1

    function display_product($name, $id, $price) {} // cool stuffs 2 3 $db = new PDO("mysql:host=127.0.0.1;dbname=test"); 4 $sql = "select p.name, p.id, p.price from products p"; 5 $stmt = $db->query($sql); 6 7 while(false !== ($prod = $stmt->fetch(PDO::FETCH_NUM))) { 8 display_product(...$prod); 9 }
  22. 30.

    How To Upgrade Turn on E_DEPRECATED and watch the logs

    of your existing platform Set with: error_reporting = E_ALL
  23. 31.

    How To Upgrade Use the PHPCompatibility PHPCS standard Install from

    https://github.com/wimg/PHPCompatibility and include in your standards directory
  24. 32.

    How To Upgrade Syntax check your code with new version

    of PHP Use phing (http://www.phing.info/): <target name="phplint" description="Run php -l over the fileset"> <phplint haltonfailure="true"> <fileset dir="src/"> <include name="**/*.php"/> </fileset> </phplint> </target> Or try my one-liner: find . -name '*.php' | xargs -n1 php -l
  25. 33.

    How To Upgrade Compile new PHP and run test suite

    with it Run tests: /path/to/php/sapi/cli/php phpunit.phar
  26. 36.

    How To Upgrade •Turn on E_DEPRECATED and watch the logs

    of your existing platform •Use the PHPCompatibility PHPCS standard •Lint check with new version (php -l) •Compile new PHP and run test suite •Run application with PHP's webserver •Upgrade a test/staging platform •Go for it!
  27. 40.

    Namespaced Functions (5.6) Have always been able to namespace functions

    Can now import them, like classes 1 include "Lib/Many/Layers/functions.php"; 2 use function \Lib\Many\Layers\deep_func; 3 4 deep_func();
  28. 41.

    Filter Handles MAC Addresses (5.5) Stealth feature (it doesn't seem

    to be documented!) 1 $mac1 = "12-34-56-78-9A-BC"; 2 var_dump(filter_var($mac1, FILTER_VALIDATE_MAC)); 3 // string(17) "12-34-56-78-9A-BC" 4 5 $mac2 = "12-34-567-A-BC"; 6 var_dump(filter_var($mac2, FILTER_VALIDATE_MAC)); 7 // bool(false)
  29. 42.

    JSON Shininess (5.4) JSONSerializable interface defines the data that is

    included when object is passed to json_encode() Also very handy additional switches to json_encode(): •JSON_PRETTY_PRINT •JSON_UNESCAPED_SLASHES •JSON_UNESCAPED_UNICODE
  30. 43.

    Reusable php://input (5.6) The php://input stream gives access to the

    incoming request body From PHP 5.6, it can be opened multiple times