[OpenWest 2014] PHP 5.NEXT: The New Bits

[OpenWest 2014] PHP 5.NEXT: The New Bits

PHP 5.5 is has been unleashed into the world; bringing some great new features including generators and coroutines, a finally construct, simple password hashing and other small changes.

Now PHP 5.6 on the horizon bringing even more changes, including variadic functions and the splat operator.

This talk is aimed at developers who use PHP every day and are looking to start new projects with the latest and greatest, or want to future-proof legacy code.

Fee39f0c0ffb29d9ac21607ed188be6b?s=128

Davey Shafik

May 08, 2014
Tweet

Transcript

  1. PHP 5.NEXT The New Bits

  2. Proprietary and Confidential •Community Engineer at Engine Yard •Author of

    Zend PHP 5 Certification Study Guide, Sitepoints PHP Anthology: 101 Essential Tips, Tricks & Hacks & PHP Master: Write Cutting Edge Code •A contributor to Zend Framework 1 & 2, phpdoc, and PHP internals • Original creator of PHAR/ PHP_Archive •@dshafik Davey Shafik
  3. The Small Stuff

  4. T_POW — The “exponent” operator

  5. Proprietary and Confidential • Double Asterisk (**) operator" • Raises

    the left operator to the right power" • Right Associative T_POW — The “exponent” operator echo 2 ** 3 ** 2; // 512 (not 64) 2 ** (3 ** 2) echo -3 ** 2; // -9 (not 9) -(3 ** 2) echo 1 - 3 ** 2; // -8 (not 4)
 1 - (3 ** 2) echo ~3 ** 2; // -10 (not 16) ~(3 ** 2)
  6. Constant Scalar Expressions

  7. Proprietary and Confidential • Use expressions when defining:" • global

    constants with const keyword" • class constants with the const keyword" • class properties" • static variables" • function arguments Constant Scalar Expressions
  8. Proprietary and Confidential • " 123 - Integers" • "

    123.456 - Floats" • " “foo” - Strings" • " __LINE__ - Line magic constant" • " __FILE__ - File magic constant" • " __DIR__ - Directory magic constant" • " __TRAIT__ - Trait magic constant" • " __METHOD__ - Method magic constant" • " __FUNCTION__ - Function magic constant" • " __NAMESPACE__ - Namespace magic constant" • " <<<HEREDOC - HEREDOC string syntax (without variables)" • " <<<'NOWDOC' - NOWDOC string syntax" • " SOME_RANDOM_CONSTANT - Constants" • " class_name::SOME_CONST - Class constants Expression Suppport
  9. Proprietary and Confidential Global constants with const keyword const FOO

    = 1 + 1; const BAR = 1 << 1; const GREETING = "HELLO"; const BAZ = GREETING." WORLD!"
  10. Proprietary and Confidential Class constants with the const keyword class

    Foo { const FOO = 1 + 1; const BAR = 1 << 1; const GREETING = "HELLO"; const BAZ = self::GREETING." WORLD!" }
  11. Proprietary and Confidential Class Properties class Foo { const BAZ

    = 10; } class Bar { public $foo = 1 + 1; public $bar = [ 1 + 1, 1 << 2, Foo::BAZ => "foo "."bar" ]; public $baseDir = __DIR__ . "/base"; }
  12. Proprietary and Confidential Static Variables const BAR = 0x10; function

    foo() { static $a = 1 + 1; static $b = [1 << 2]; static $c = 0x01 | BAR; }
  13. Proprietary and Confidential Function Arguments const  BAR  =  1;  

        function  f($a  =  1  +  1,  $b  =  2  <<  3,  $c  =  BAR?10:100)  {   }
  14. __debugInfo()

  15. Proprietary and Confidential • Magic method to control the output

    of var_dump() __debugInfo() class File { // "Resource(stream)" isn't all that useful private $fp; // But all the stream meta data is public function __debugInfo() { return $this->fp ? stream_get_meta_data($fp) : []; } public function open($filename, $mode = 'r'){ $this->fp = fopen($filename, $mode); } }
  16. Proprietary and Confidential __debugInfo() (Cont.) $f = new File; var_dump($f);

    // object(File)#1 { } $f->open('http://php.net'); var_dump($f); /* object(File)#1 { ["wrapper_type"]=> string(4) "http" ["stream_type"]=> string(10) "tcp_socket" etc... */
  17. GMP Improvements + Operator Overloading

  18. Proprietary and Confidential • GMP switches to use objects, instead

    of resources" • Serializable" • Castable" • var_dump()able" • Operator Overloading" • Internal Only :(! • Allows objects to define the behavior when used as operands with:" • Basic Math Operators: + - * / % • Bitshifting: << >> • Concat: ." • Boolean Operators: | & ^ XOR ~ ! GMP Improvements + Operator Overloading
  19. Proprietary and Confidential GMP Improvements + Operator Overloading $result  =

     gmp_mod(          gmp_add(                  gmp_mul($c0,  gmp_mul($ms0,  gmp_invert($ms0,  $n0))),                  gmp_add(                          gmp_mul($c1,  gmp_mul($ms1,  gmp_invert($ms1,  $n1))),                          gmp_mul($c2,  gmp_mul($ms2,  gmp_invert($ms2,  $n2)))                  )          ),          gmp_mul($n0,  gmp_mul($n1,  $n2))   );
  20. Proprietary and Confidential GMP Improvements + Operator Overloading $result  =

     (          $c0  *  $ms0  *  gmp_invert($ms0,  $n0)      +  $c1  *  $ms1  *  gmp_invert($ms1,  $n1)      +  $c2  *  $ms2  *  gmp_invert($ms2,  $n2)   )  %  ($n0  *  $n1  *  $n2);
  21. phpdbg SAPI

  22. Proprietary and Confidential • GDB-like debugger for PHP" • Stand-alone

    SAPI, like CLI, CGI, or php-fpm" • Not an extension like xdebug/Zend Debugger! • Full featured" • Break on file, function, method, opline address, current file line #, expressions, conditions, and opcodes" • Full disassembly" • Remote debugging phpdbg SAPI
  23. Proprietary and Confidential

  24. Import Namespaced Functions & Constants

  25. Proprietary and Confidential • Prior to PHP 5.6:" • Outside

    of the namespace, function names/constants had to be fully qualified" • You could alias the namespace to shorten it (ugh!)" " • Add two new keyword sequences:" • use function \foo\bar\function" • use const \foo\bar\BAZ" • Use commas to import multiples Import Namespaced Functions & Constants
  26. Proprietary and Confidential Import Namespaced Functions & Constants namespace foo\bar

    { const HELLO_WORLD = "Hello World"; function strlen($str) { return \strlen($str); } } namespace { use function foo\bar\strlen; use function foo\bar\non_existent; // Doesn't exist! use const foo\bar\HELLO_WORLD; var_dump(strlen(HELLO_WORLD)); // not ambiguous var_dump(non_existent()); // Does not fall-through // to global scope: fatal error }
  27. Proprietary and Confidential • Great for DSLs! Import Namespaced Functions

    & Constants use function html\div, html\p, html\em; $html = div(p('Some', em('Text')));
  28. Variadic Functions

  29. Variadic Syntax … $variable

  30. Proprietary and Confidential • Variadic means to accept a variable

    number of arguments" • Previously you needed to use func_num_args()/func_get_args()" • Which includes defined arguments also!" • New syntax: "… $variable" (triple dot)" • Array with just the variable arguments" • Self-documenting code" • Supports by-reference" • Allows type hints" • Must be the last argument! Variadic Functions
  31. Variadic Functions function fn($reqParam, $optParam = null, ...$params) { var_dump($reqParam,

    $optParam, $params); } fn(1); // 1, null, [] fn(1, 2); // 1, 2, [] fn(1, 2, 3); // 1, 2, [3] fn(1, 2, 3, 4); // 1, 2, [3, 4] fn(1, 2, 3, 4, 5); // 1, 2, [3, 4, 5]
  32. Variadic Functions — References class MySQL implements DB { public

    function prepare($query, &...$params) { $stmt = $this->pdo->prepare($query); foreach ($params as $i => &$param) { $stmt->bindParam($i + 1, $param); } return $stmt; } // ... } $stmt = $db->prepare('INSERT INTO users 
 (name, email, age) VALUES (?, ?, ?)', $name, $email, $age);
 foreach ($usersToInsert as list($name, $email, $age)) { $stmt->execute(); }
  33. Variadic Functions — Type hints function hooks($name, Callable ... $callbacks)

    { foreach ($callbacks as $callback) { $callback(); } }
  34. Argument Unpack (AKA: SPLAT)

  35. Splat Syntax … $variable

  36. Splat Syntax function fn(… $variable)

  37. Proprietary and Confidential • The opposite of variadics, unpack an

    array (or similar) as arguments" • No more call_user_func_array() (which is “slow”)" • Valid for any argument list (including new foo(… $var))" • Must be at the end of the argument list" • Use it multiple times! Splat
  38. Splat function test(...$args) { var_dump($args); } test(1, 2, 3); //

    [1, 2, 3] test(...[1, 2, 3]); // [1, 2, 3] test(...new ArrayIterator([1, 2, 3])); // [1, 2, 3]
  39. Splat $args1 = [1, 2, 3]; $args2 = [4, 5,

    6]; test(...$args1, ...$args2); // [1, 2, 3, 4, 5, 6] test(1, 2, 3, ...$args2); // [1, 2, 3, 4, 5, 6] test(...$args1, 4, 5, 6); // [1, 2, 3, 4, 5, 6]
  40. What Next?

  41. HHVM

  42. Proprietary and Confidential • Alternative PHP runtime from Facebook" •

    Super Fast" • Close to feature parity" • Mostly just missing some key extensions" • Crazy Fast (no really) HHVM
  43. Proprietary and Confidential • The most un-googleable name for a

    thing, ever" • A “new” language based on PHP that supports strong type hinting" • Mostly a dev-tool: instant static analysis can detect bugs and other issues during development" • Ignored during runtime" • Uses <?hh open tag" • Can co-exist with <?php, or be used exclusively with <?hh // strict" • Supports native X(HT)ML (XHP)" • Easy Parallelization with async functions HHVM: Hack
  44. HHVM: Hack — Type hints <?hh function echo_upper(string $s) {

    echo (strtoupper($s)); } function sum(array<int> $a) { return array_reduce($a, ($sum, $i) ==> $sum + $i); }
  45. Proprietary and Confidential • Enhanced/Specialized Arrays" • OO interface for

    arrays" • Frozen* and Mutable* variants HHVM: Hack — Vectors, Sets, Maps <?hh $v = Vector {"d", "c", "b"}; $v->add("a"); $v->reverse(); $v = $v ->map(($_) ==> strtoupper($_)) ->filter(($_) ==> strcmp($_, "D") < 0);
  46. HHVM: Hack — Native X(HT)ML <?hh $v = Vector {"d",

    "c", "b"}; $v->add("a"); $v->reverse(); $v = $v->map(($_) ==> strtoupper($_))->filter(($_) ==> strcmp($_, "D") < 0); $items = <ul />; foreach ($v as $i) { $items->appendChild(<li>{$i}</li>); } echo <div>Vector:{$items}</div>; // A, B, C $m = Map {"a" => 1, "b" => 2}; $m->add(Pair {"d", 4}); echo <div>Map: <ul> <li>contains "a": {$m->contains("a") ? "yes" : "no"}</li> // yes <li>contains "c": {$m->contains("c") ? "yes" : "no"}</li> // no <li>size: {$m->count()}</li> // 3 </ul> </div>;
  47. ReactPHP Asynchronous Event-based Applications

  48. ReactPHP reactphp.org

  49. ReactPHP $app = function ($request, $response) { $response->writeHead(200,['Content-Type' => ‘text/plain']);

    $response->end("Hello World\n"); }; $loop = React\EventLoop\Factory::create(); $socket = new React\Socket\Server($loop); $http = new React\Http\Server($socket, $loop); $http->on('request', $app); echo "Server running at http://127.0.0.1:8080\n"; $socket->listen(8080); $loop->run(); Uses LibEV, LibEvent or Streams Socket Select
  50. Proprietary and Confidential " • Async Redis Client" • ZeroMQ,

    Stomp Support" • Promises (CommonJS Promises/A)" • Partials" • GifSocket
 "Real Time communication library using Animated Gifs as a transport™" - Alvaro Videla. ReactPHP
  51. Proprietary and Confidential Feedback & Questions: " Feedback: https://joind.in/11173
 Twitter:

    @dshafik Email: davey@engineyard.com Slides: http://daveyshafik.com/slides