PHP 7: Cool & Exciting Features

Php community is very happy with the new release of latest release PHP 7. It doesn’t mean that PHP’s old version has not been working properly. On the contrary, some little bit changes in the next version brought many changes to its features. These new changes are about the support of Object-Oriented programming and many features associated with that. PHP 7 beta version was released on November 12, 2015. It has been making technical decisions since then. PHP 7 has taken huge improvement in matters related to speed and performance.

The blog is all about the clearing doubts you may have about what all changes and updates you can expect from PHP 7.

The Zend Engine-

To increase the performance of PHP applications, PHP 7 uses the latest Zend Engine having code-name as PHPNG(PHP Next-Gen). It doubles the performance of PHP.

PHP 7 twice as fast as PHP 5.6 –

PHP 7 runs applications faster in performance as compared to  those running on PHP 5.6. This is because of the new PHPNG engine. According to PHP founder Rasmus Lerdorf, the upgrade means using less number of servers, while still serving the same number of users. The Just-in-time compilation (JIT) is another speed catalyst, which allows run time compilation before execution. 

Dependable 64-bit support-

As it provides dependable 64-bit support means no more slow data operations. Due to this, arrays and variables are more ably handled. Applications that require large data arrays will get benefit of it. For eg., Scientific applications, data management, digital media related and CAD-like functionality programs. Performance is increased and this is because of the 64-bit.   

New Features of PHP 7-

1. Anonymous Classes-

  1. Anonymous function is for creating the scope to create anonymous class objects, especially in creating one-off objects. Support for this feature has been added in PHP 7.  By using efficiently, they can execute and code quickly.

      //Pre-PHP 7 code-

    Class Logger

      {

         public function log($msg)

            {

                echo $msg;

            }

      }

$util->setLogger(new Logger());

//PHP 7+ code

$util->setLogger(new class 

{

      public function log($msg)

       {

           echo $msg;

       }

};

2. Return Type Declarations-

This is another one developer-friendly add-on. Most of the developers prefer declaring the function’s return type. Any type, including objects and arrays can be returned. As a result, the execution works faster and passing control to the line from where it is called. 

function arraysSum(array…$arrays): array

{

          return array_map(function(array $array): int

    {

            return array_sum($array);

    }, $arrays);

}

print_r(arraysSum([1,2,3], [4,5,6], [7,8,9]));

/* Output

Array

(

[0] => 6

[1] => 15

[2] => 24

)

*/

3. Group Use Declarations- 

This new feature is for those developers who want to use the same namespace to import several classes. Code is relatively neat and it also saves the typing time. Debugging of the code get easier because of the group use declarations. This helps to identify imports that are part of the same module. Example is as follows:

// Pre PHP 7 code

use some\namespace\ClassA;

use some\namespace\ClassB;

use some\namespace\ClassC as C;

use function some\namespace\fn_a;

use function some\namespace\fn_b;

use function some\namespace\fn_c;

use const some\namespace\ConstA;

use const some\namespace\ConstB;

use const some\namespace\ConstC;

// PHP 7+ code

use some\namespace\{ClassA, ClassB, ClassC as C};

use function some\namespace\{fn_a, fn_b, fn_c};

use const some\namespace\{ConstA, ConstB, ConstC};

4. Scalar Type Declarations- 

This is a new feature which makes use of strings, floats, integers as type hints for methods and functions. It is by default non restrictive. It will allow float value to integer parameter, just coerce it to int without error. Scalar type hints is already present in C, C++ and Java and now it came in PHP 7.

// Coercive mode

function sumOfInts(int . . .$ints)

   {

      return array_sum($ints);

   }

var_dump(sumOfInts(2, ‘3’ , 4.1));   //int (9)

5. Null Coalescing and Spaceship Operator-

The null coalescing operator is represented like this ??. It’s used to check if the value is set or null, or in other words, if the value is exists and not null, then it returns the first operand, otherwise it returns the second operand.

// Pre PHP 7 code

$route = isset($_GET[‘route’]) ? $_GET[‘route’] : ‘index’;

// PHP 7+ code

$route = $_GET[‘route’] ?? ‘index’;

The Spaceship operator is represented like this <=>. It is used to compare two expressions and return -1, 0, 1 when one variable is less than, equal to, or greater than, as compared to the other variable.The functionality of the spaceship operator, officially called the Combined Comparison Operator can be availed to make the chained comparison more compact.
// compares strings lexically

var_dump(‘PHP’ <=> ‘Node’); // int(1)

// compares numbers by size

var_dump(123 <=> 456); // int(-1)

// compares corresponding array elements with one-another

var_dump([‘a’, ‘b’] <=> [‘a’, ‘b’]); // int(0)

6. Implementation of Error Handling-

The new Error Handling techniques implemented in PHP 7. Handling fatal errors was a dream in previous versions of PHP. If a fatal error occurs, it just simply stops the script rather than invoking the error handler. But now, PHP 7 allows an exception to be thrown when an error occurs, rather than stopping the whole script. This mean that Fatal errors are gone from PHP 7. One more thing to focus here is other types of errors like warnings and notices are unchanged in PHP 7. And exceptions are only thrown by fatal and recoverable errors only. However, Error and Exception both in PHP 7 implements the new throwable class. This means both work almost the same way. Let’s see the new hierarchy to understand more.

-> Exception implements Throwable

    -> …

-> Error implements Throwable

    -> TypeError

    -> ParseError

    -> ArithmeticError

        -> DivisionByZeroError

    -> AssertionError

Under Error, PHP 7 now have some more specific errors. Which includes ParseError, TypeError, ArithmeticErrors and an AssertionError. Practically all errors that were fatal in PHP 5, now throw instances of Error in PHP 7, which in term help you to improve your code legibility.

Conclusion-

There are some features that have been removed in PHP 7. Versions released before 5.5 are not compatible any longer. Now it is your decision to decide whether to upgrade to PHP 7 for super fast speeds and update all your code accordingly. Or stay with the previous version of PHP.

If you’re interested in adopting PHP for development at your business, then Solace Infotech is an ideal place to start development. We at Solace believe in the benefits and effectiveness of using PHP 7 for development. Dedicated experts at Solace will surely give you the best PHP development solution to your business. Contact us for effective PHP development that will grow your business to next level.