Pro Yearly is on sale from $80 to $50! »

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

Fee39f0c0ffb29d9ac21607ed188be6b?s=47 Davey Shafik
February 21, 2014

[PHPUK 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

February 21, 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 •@dshafik Davey Shafik
  3. About These Slides

  4. Proprietary and Confidential • Two slides per “slide”! – Title

    Slide (for when I’m talking)! – Details slide (for later)! • Nobody likes it when you can read the slide just as well as the speaker can! • I like slides that are useful About These Slides
  5. The Small Stuff

  6. T_POW — The “exponent” operator

  7. 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)
  8. Constant Scalar Expressions

  9. 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
  10. 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
  11. Proprietary and Confidential Global constants with const keyword const FOO

    = 1 + 1; const BAR = 1 << 1; const GREETING = "HELLO"; const BAZ = GREETING." WORLD!"
  12. 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!" }
  13. 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"; }
  14. Proprietary and Confidential Static Variables const BAR = 0x10; function

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

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

  17. 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); } }
  18. 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... */
  19. GMP Improvements + Operator Overloading

  20. 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
  21. 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))   );
  22. 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);
  23. phpdbg SAPI

  24. 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
  25. Proprietary and Confidential

  26. Import Namespaced Functions & Constants

  27. 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
  28. 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 }
  29. Proprietary and Confidential • Great for DSLs! Import Namespaced Functions

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

  31. Variadic Syntax … $variable

  32. 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
  33. 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]
  34. 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(); }
  35. Variadic Functions — Type hints function hooks($name, Callable ... $callbacks)

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

  37. Splat Syntax … $variable

  38. Splat Syntax function fn(… $variable)

  39. 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))! • No limitations on placement! • Use it multiple times! Splat
  40. 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]
  41. 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]
  42. What Next?

  43. HHVM

  44. 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
  45. 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
  46. 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); }
  47. 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);
  48. 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>;
  49. ReactPHP Asynchronous Event-based Applications

  50. ReactPHP reactphp.org

  51. 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
  52. 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
  53. Proprietary and Confidential Feedback & Questions: Feedback: https://joind.in/10691
 Twitter: @dshafik

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