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

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

Davey Shafik

May 08, 2014
Tweet

More Decks by Davey Shafik

Other Decks in Programming

Transcript

  1. 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
  2. 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)
  3. 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
  4. 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
  5. Proprietary and Confidential Global constants with const keyword const FOO

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

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

        function  f($a  =  1  +  1,  $b  =  2  <<  3,  $c  =  BAR?10:100)  {   }
  10. 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); } }
  11. 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... */
  12. 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
  13. 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))   );
  14. 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);
  15. 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
  16. 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
  17. 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 }
  18. Proprietary and Confidential • Great for DSLs! Import Namespaced Functions

    & Constants use function html\div, html\p, html\em; $html = div(p('Some', em('Text')));
  19. 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
  20. 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]
  21. 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(); }
  22. Variadic Functions — Type hints function hooks($name, Callable ... $callbacks)

    { foreach ($callbacks as $callback) { $callback(); } }
  23. 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
  24. 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]
  25. 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]
  26. 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
  27. 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
  28. 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); }
  29. 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);
  30. 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>;
  31. 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
  32. 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