What’s New in PHP 7 ?

Pre-requisite: PHP 7 | Features Set 1

PHP 5 seen many minor releases, being exciting along the way, including the provision of Object-Oriented programming and many features correlated with it.

So, why 7 and not 6?
Almost all the features being considered for PHP 6 were ultimately executed in PHP 5.3 and succeeding, so nothing missed. Eventually, a new means for feature requests were put. When the trait set for a significant release was accepted, to avoid confusion it skipped to version 7 for the newest release.

What makes PHP 7 unique?
Speed and performance just got better with PHP 7 – less memory used by PHP codebase, a faster engine developed, being said that, let’s take a look what has been added into this package

  • Constant arrays using define(): JavaScript array constant can be defined by using define() function. In PHP 5.6 it defined by const keyword.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Use define() function
    define('GFG'
        ['Geeks', 'G4G', 'geek']
    );
      
    // Display content
    echo GFG[0];
    ?>

    chevron_right

    
    

    Output:

    Geeks
    
  • Unicode Escaping: PHP 7.0.0 has introduced the “Unicode codepoint escape”. It uses a Unicode codepoint in hexadecimal form and outputs that codepoint in UTF-8 to a double-quoted string. Any legitimate codepoint is allowed, including starting 0’s being arbitrary. So it is possible to write Unicode characters efficiently by using a double-quoted or a heredoc string, without calling a function.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Write PHP code
    echo "\u{aa}";
    echo "\u{0000aa}";
    echo "\u{9999}";
    ?>

    chevron_right

    
    

    Output:

    ªª�
    

    One could do character escaping before too but using PHP 7 it is much easier. Including the Unicode within a string without a hassle.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Write PHP code
    echo 'You owe me £500.';
    ?>

    chevron_right

    
    

    Output:

    You owe me £500.
    

    In this example, there exist standard A to Z and 0 to 9 characters in use. But it does hold a special character the pound symbol (£). Earlier, it was necessary to escape these characters, which would otherwise produce its character code 163 in the string. So the output could look like 163500 or something to that effect. This would be a nightmare, hence we have to escape the pound symbol every time which would have caused an error otherwise.
    So how to use Unicode escaping? Unicode practices hexadecimal to define the number, take a look at the resulting

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Write PHP code
    echo 'You owe me \u{A3}500.';

    chevron_right

    
    

    This would also render correctly:

    You owe me £500.

    So the backslash u and braces ( \u{} ) are the essential syntax for inserting a Unicode hexadecimal character within the string.

  • Filtered Unserialize(): This feature is used to provide a better security when unserializing objects on untrusted data. It provides code injections. Security is the major importance to us which provides better with unserializing objects on data from an unknown source or which is untrusted, thus enabling the developer to whitelist classes that can be unserialized. It takes a single serialized variable and returns a PHP value.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Write PHP code
    class A { 
        public $obj1var;   
    }
    class B {
        public $obj2var;
    }
      
    $obj1 = new A();
    $obj1->obj1var = 10;
      
    $obj2 = new B();
    $obj2->obj2var = 20;
      
    $serializedOb1 = serialize($obj1);
    $serializedOb2 = serialize($obj2);
       
    // If allowed_classes is passed as
    // false, unserialize transforms
    // every all objects in
    // __PHP_Incomplete_Class object
    $data = unserialize($serializedOb1,
             ["allowed_classes" => true]);
        
    // Converts all objects into 
    // __PHP_Incomplete_Class object
    // except those of A and B
    $data2 = unserialize($serializedOb2
         ["allowed_classes" => ["A", "B"]]);
        
    print($data->obj1var);
    print("<br/>");
    print($data2->obj2var);
      
    ?>

    chevron_right

    
    

    Output:

    10
    20
  • Group Use Declaration: PHP 7 has implemented the concept of Group in the PHP namespace. This is one of the excellent addition to namespaces in PHP 7. They are more straightforward and makes it simpler to import classes, constants, and functions in a compact way. Group use declarations present the ability to import multiple structures from a standard namespace and cuts a good level of verbosity in most cases. Group use declarations make it simpler to identify the various imported entities belong to the equivalent module.
  • Expectations: We all have certain assumptions but not all of these assumptions are facts. Assumptions are based on logic and hunch, but it doesn’t address them as facts. The assumptions may seem logical in your mind but they should be backed up by code in order to protect the processing integrity. Expectations signify a backward compatible improvement to the older assert() function. It presents the capability to cast custom exceptions if the assertion defaults. assert() the first parameter is an expression as compared to being a string or Boolean to be examined.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Write PHP code
    $num = 300;
      
    echo assert( $num > 600, new CustomError(
            "Assumed num was greater than 600"));
      
    ?>

    chevron_right

    
    

    Output:

    1
    
  • Session Options: PHP 7 introduces session_start() to allow an array of options that override the configuration directives frequently set in php.ini.
    For example, the directive session.cache_expire is 180 but let’s say I want longer than this for my cache to expire for a particular session.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Write PHP code
    session_start( [
        cache_expire => 380
    ] );

    chevron_right

    
    

    Now one doesn’t have to change this option by reconfiguring the server settings.

  • Generator Return Expressions: PHP 5.5 had introduced Generator Function which included yield values and the return statement had to be the last statement within it.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    // Write PHP code
    function genA() {
        yield 20;
        yield 30;
        yield 40;
        return 50;
    }

    chevron_right

    
    

    According to the PHP manual, “a generator function looks like a normal function excepts that instead of returning a value, a generator yields as many values as it needs to. Any function containing yield is a generator” function. It can iterate and retrieve the values but if one tried to return anything from it, an error would be thrown.

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    $genObj = function (array $number) {
        foreach($number as $num) {
            yield $num * $num;
        }  
        return "Done calculating the square.";  
    };
       
    $result = $genObj([10, 20, 30, 40, 50]);
       
    foreach($result as $value) {
       echo $value . PHP_EOL;
    }
       
    // Grab the return value
    echo $result->getReturn(); 
      
    ?>

    chevron_right

    
    

    Output:

    100
    400
    900
    1600
    2500
    Done calculating the square.
    
  • Generator delegation: In PHP 7, generator delegation is the yield value from another generator, a traversable object, or an array using the yield from keyword. The outer generator will then yield all values from the inner generator, objects, or array until that is no longer valid, after which execution will continue in the outer generator. If a generator is used with yield from, the yield from expression will also return any value returned by the inner generator.
    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?php
      
    // Write PHP code
    function mul(array $number) {
        foreach($number as $num) {
            yield $num * $num;
        }  
        yield from sub($number);
    };
       
    function sub(array $number) {
        foreach($number as $num) {
            yield $num - $num;
        }  
    }
       
    foreach(mul([1, 2, 3, 4, 5]) as $value) {
        echo $value . PHP_EOL;
    }
      
    ?>

    chevron_right

    
    

    Output:

    1
    4
    9
    16
    25
    0
    0
    0
    0
    0
    

Reference: http://php.net/manual/en/migration70.new-features.php



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.