Facebook Twitter Instagram
    TecAdmin
    • Home
    • Ubuntu 20.04
      • Upgrade Ubuntu
      • Install Java
      • Install Node.js
      • Install Docker
      • Install LAMP Stack
    • Tutorials
      • AWS
      • Shell Scripting
      • Docker
      • Git
      • MongoDB
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    Home»Programming»PHP»5 New Features in PHP 7

    5 New Features in PHP 7

    Guest UserBy Guest UserFebruary 16, 20167 Mins Read

    Author Bio

    This Case Study is a guest post written by Kaira Clark works at Xicom Technologies Ltd – A CakePHP web Application Development company. she’s always happy to share her passion for Marketing and web development. If you’re planning to Hire Dedicated Team for a Brilliant online presence, she is the one for you.

    5 New Features in PHP 7

    All things considered, 2015 has been an essential year for every PHP designers, and following eleven years, PHP adaptation to 5.0 release, there is another development that is, in the long run, coming your way. However, consider over different development highlights, think about what method would your PHP variant effect your current PHP codebase? Simply evaluate what truly has changed in PHP? How securely can you deal with PHP redesigns? Here, in this post, you will get every solution for your inquiries and will in the end experience what is coming your way while you are working with PHP 7. So, let’s come to the heart of the matter of examination now.

    PHP 7

    Execution Improvements

    Execution upgrades are most likely one of the primary motivation among developers on why everybody ought to have a report on each server when there is an arrival of PHP stable variant is released. The center refactoring presented by the phone RFC makes PHP 7 faster than HHVM. The official benchmarks are noteworthy: most of the normal applications running on PHP 5.6 will keep executing in every event twice as faster on PHP 7.

    Backwards Compatibility Pitfalls

    Now, let us have a conversation over few essential PHP factors that could eventually break down a legacy application running on older PHP versions.

    • Uniform Variable Syntax

    Solves a series of every inconsistency at the time of evaluating variable-variable expressions. Consider the below code shown:

    class Company
    {
       public $emp_name = 'Madhur;
       public $emp_des = 'Software Engineer';
    }
    
    $company = new Company();
    $property = [ 'first' => 'emp_name', 'second' => 'info' ];
    echo "nEmployee name is " . $company->$property['first'] . "nn";
    

    In PHP 7, the expression $company->$property[‘first’] is evaluated as {$company->$property}[‘first’]. The interpreter will evaluate $company->$property first.

    Thanks to our new uniform left-to-right variable syntax that makes every expression valid which was not possible in early PHP version. Consider the following class for better understanding:

    class Company
    {
       public static $location = 'NCR';
       public function getBranches()
       {
           return [
               'jaipur' => function () {
                   return ''east and west;
               },
               'chandigarh' => function () {
                   return 'north and south';
               }
           ];
       }
    
       public function getBranchesOf($someone)
       {
           return $this->getBranches()[$someone];
       }
    
       public static function getNewCompany()
       {
           return new Company();
       }
    }
    
    

    PHP 7 makes it possible to create nested associations with different combinations between operators:

    $company = new Company();
    echo "n" . $company->getBranches()['jaipur']() . "nn";
    echo "n" . $company->getBranchesOf('chandigarh')() . "nn";
    

    This code snippet would generate a parse error on PHP 5, but goes well with PHP 7.

    Working with Fatal Error with multiple “default” clauses

    This is, again a controversial case that relates to more logical errors. It does not make use of multiple default clauses in a switch just because it never occurred any error warnings. In PHP 7 you will come across a Fatal Error: “Switch statements only contain one default clause”.

    Engine Exceptions in PHP

    Engine exceptions work as an error handling procedure in the application. So, all your existing fatal and recoverable fatal errors are efficiently replaced by exceptions, to easily catch all the said errors and take action against to handle such errors.

    Let’s refer to the code below about how to handle implementation of engine exceptions to keep backwards compatibility easy:

    set_error_handler(function ($code, $message) {
       echo "ERROR $code: " . $message . "nn";
    });
    
    function a(ArrayObject $b){
       return $b;
    }
    
    a("test");
    
    echo "Hello World";
    

    This code effectively recovers error that are caused by the type mismatch when you call the function a() with the help of string as a parameter.

    Hello World

    This execution will continue because an error was handled efficiently. In PHP 7, it will generate a TypeError exception that is not an error. So in this case, a custom error handler won’t be called, and this is the output below that you will come across:


    Fatal error: Uncaught TypeError: Argument 1 passed to a() must be an instance of ArrayObject, string given, called in /vagrant/tests/test04.php on line 12 and defined in /vagrant/tests/test04.php:7
    Stack trace:
    #0 /vagrant/tests/test04.php(12): a('test')
    #1 {main}
    thrown in /vagrant/tests/test04.php on line 7

    Here an execution will stop as the exception is not caught. To overcome this issue, one should find the exceptions by making use of try/catch blocks. Notice that the Exception hierarchy will change to accommodate on the new engine exceptions with minimal legacy code. Refer to the following pattern below:

    • Throwable interface
      • Exception implements Throwable
        • ErrorException extends Exception
        • RuntimeException extends Exception
      • Error implements Throwable
        • TypeError extends Error
        • ParseError extends Error
        • AssertionError extends Error

    The above pattern signifies that a new catch-all Exception is now a Throwable instead of Exception.

    Newly Added Language Features

    Let’s see what it includes?
    New Operators

    1. -> Spaceship/ Comparison operator
    The spaceship operator is denoted as <=>, also known by a name combined comparison operator that are used to enable a chained comparison.

    It has a following expression:
    $a <=> $b

    1. Expression evaluates to -1 if $a is smaller than $b
    2. 0 if $a equals $b
    3. 1 if $a is greater than $b.

    Overall it can be used as following expression:

    ($a < $b) ? -1 : (($a > $b) ? 1 : 0)

    2 -> The null coalesce operator is denoted as ?? that keeps a check whether a value is set to use it.

    Scalar Type Hints

    Scalar type hints come as one of the most well-known attributes that are included in PHP language that makes use of integers, floats, strings, and Boolean symbols as type hints to work with functions and methods. Scalar type hints are non-restrictive by default that signifies that when you pass a float value to an integer, parameter, it will just suppress it to ignite format without any error warnings.

    So, to overcome this issue, it is essential to enable a strict mode that will throw errors when any illegal scalar type is passed as an argument. Let’s refer to below generated code:

    function double(int $value)
    {
       return 2 * $value;
    }
    $a = double("5");
    var_dump($a);
    

    To make sure that integers are allowed to be passed to double function, then enable a strict mode by including the directive declare(strict_types = 1) patterns as a first line in your script:

    declare(strict_types = 1);
    function double(int $value)
    {
       return 2 * $value;
    }
    $a = double("5");
    var_dump($a);
    

    This code will generate a Fatal error: Uncaught TypeError: Argument 1 passed to double() should be of the type integer, string given.

    Return Type Hints

    Another significant new feature that is added to PHP 7 is its extreme capability to enable the return type of methods as well as functions; that behaves as a scalar type hints. Watch out the below-generated code:

    function a() : bool
    {
       return 1;
    }
    var_dump(a());
    

    This code snippet runs efficiently without warnings, and the returned value is converted into bool format automatically. By activating strict mode, a fatal error is generated:

    Fatal error: Uncaught TypeError: Return value of a() must be of the type boolean, integer returned

    These errors are a kind of Exceptions that are caught and handled by using try/catch blocks.

    Conclusion

    I hope you will enjoy working with all new version of PHP 7. Read more

    PHP PHP 7
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp
    Previous ArticleHow To Install WordPress with Nginx on Ubuntu 18.04 & 16.04
    Next Article How To Install KDE Plasma 5.10 on Ubuntu 17.04/16.04, Debian 8 & LinuxMint 18

    Related Posts

    How To Install PHP (8.1, 7.4 or 5.6) on Ubuntu 22.04

    Updated:May 9, 20223 Mins Read

    How To Install Linux, Nginx, MySQL, & PHP (LEMP Stack) on Ubuntu 22.04

    Updated:April 7, 20227 Mins Read

    How To Install LAMP Stack on Ubuntu 22.04 LTS

    Updated:April 20, 20225 Mins Read

    How To Setup Apache, PHP & MongoDB in Ubuntu & Debian

    Updated:October 8, 20213 Mins Read

    How To Install and Use PHP Composer on Debian 11

    Updated:February 16, 20224 Mins Read

    How To Install PHP (8.1, 7.4 & 5.6) on Debian 11

    Updated:February 16, 20224 Mins Read

    2 Comments

    1. Arpita Singh on December 1, 2016 12:43 pm

      Hello KAIRACLARK

      First I would like to thank you for sharing such an informative content. It is really helpful for me.

      Thank and regards

      Arpita Singh

      Reply
    2. czechiaa on February 22, 2016 8:44 am

      ‘jaipur’ => function () {
      return ”east and west;
      }, ….

      Haha 😉

      Reply

    Leave A Reply Cancel Reply

    Recent Posts
    • How to Install JAVA on Ubuntu 22.04
    • Switching Display Manager in Ubuntu – GDM, LightDM & SDDM
    • Changing the Login Screen Background in Ubuntu 22.04 & 20.04
    • How To Install PHP (8.1, 7.4 or 5.6) on Ubuntu 22.04
    • (Resolved) Please install all available updates for your release before upgrading
    Facebook Twitter Instagram Pinterest
    © 2022 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.