$30 off During Our Annual Pro Sale. View Details »

[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. PHP 5.NEXT
    The New Bits

    View Slide

  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

    View Slide

  3. The Small Stuff

    View Slide

  4. T_POW — The “exponent” operator

    View Slide

  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)

    View Slide

  6. Constant Scalar Expressions

    View Slide

  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

    View Slide

  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"
    • " <<• " <<<'NOWDOC' - NOWDOC string syntax"
    • " SOME_RANDOM_CONSTANT - Constants"
    • " class_name::SOME_CONST - Class constants
    Expression Suppport

    View Slide

  9. Proprietary and Confidential
    Global constants with const keyword
    const FOO = 1 + 1;
    const BAR = 1 << 1;
    const GREETING = "HELLO";
    const BAZ = GREETING." WORLD!"

    View Slide

  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!"
    }

    View Slide

  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";
    }

    View Slide

  12. Proprietary and Confidential
    Static Variables
    const BAR = 0x10;
    function foo() {
    static $a = 1 + 1;
    static $b = [1 << 2];
    static $c = 0x01 | BAR;
    }

    View Slide

  13. Proprietary and Confidential
    Function Arguments
    const  BAR  =  1;  
       
    function  f($a  =  1  +  1,  $b  =  2  <<  3,  $c  =  BAR?10:100)  {  
    }

    View Slide

  14. __debugInfo()

    View Slide

  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);
    }
    }

    View Slide

  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...
    */

    View Slide

  17. GMP Improvements + Operator Overloading

    View Slide

  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

    View Slide

  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))  
    );

    View Slide

  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);

    View Slide

  21. phpdbg SAPI

    View Slide

  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

    View Slide

  23. Proprietary and Confidential

    View Slide

  24. Import Namespaced Functions & Constants

    View Slide

  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

    View Slide

  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
    }

    View Slide

  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')));

    View Slide

  28. Variadic Functions

    View Slide

  29. Variadic Syntax
    … $variable

    View Slide

  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

    View Slide

  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]

    View Slide

  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();
    }

    View Slide

  33. Variadic Functions — Type hints
    function hooks($name, Callable ... $callbacks) {
    foreach ($callbacks as $callback) {
    $callback();
    }
    }

    View Slide

  34. Argument Unpack (AKA: SPLAT)

    View Slide

  35. Splat Syntax
    … $variable

    View Slide

  36. Splat Syntax
    function fn(… $variable)

    View Slide

  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

    View Slide

  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]

    View Slide

  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]

    View Slide

  40. What Next?

    View Slide

  41. HHVM

    View Slide

  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

    View Slide

  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 • Can co-exist with • Supports native X(HT)ML (XHP)"
    • Easy Parallelization with async functions
    HHVM: Hack

    View Slide

  44. HHVM: Hack — Type hints
    function echo_upper(string $s) {
    echo (strtoupper($s));
    }
    function sum(array $a) {
    return array_reduce($a, ($sum, $i) ==> $sum + $i);
    }

    View Slide

  45. Proprietary and Confidential
    • Enhanced/Specialized Arrays"
    • OO interface for arrays"
    • Frozen* and Mutable* variants
    HHVM: Hack — Vectors, Sets, Maps
    $v = Vector {"d", "c", "b"};
    $v->add("a");
    $v->reverse();
    $v = $v
    ->map(($_) ==> strtoupper($_))
    ->filter(($_) ==> strcmp($_, "D") < 0);

    View Slide

  46. HHVM: Hack — Native X(HT)ML
    $v = Vector {"d", "c", "b"};
    $v->add("a");
    $v->reverse();
    $v = $v->map(($_) ==> strtoupper($_))->filter(($_) ==> strcmp($_, "D") < 0);
    $items = ;
    foreach ($v as $i) {
    $items->appendChild({$i});
    }
    echo Vector:{$items}; // A, B, C
    $m = Map {"a" => 1, "b" => 2};
    $m->add(Pair {"d", 4});
    echo Map:

    contains "a": {$m->contains("a") ? "yes" : "no"} // yes
    contains "c": {$m->contains("c") ? "yes" : "no"} // no
    size: {$m->count()} // 3

    ;

    View Slide

  47. ReactPHP
    Asynchronous Event-based Applications

    View Slide

  48. ReactPHP
    reactphp.org

    View Slide

  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

    View Slide

  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

    View Slide

  51. Proprietary and Confidential
    Feedback & Questions: "
    Feedback: https://joind.in/11173

    Twitter: @dshafik
    Email: [email protected]
    Slides: http://daveyshafik.com/slides

    View Slide