PHP 7: Cool & Exciting Features

PHP 7: Cool & Exciting Features

PHP 7

If there ever was a time for all you web developers and website owners (having sites powered by PHP-enabled CMS) out there to be delighted, it is now. After a long wait of more than 11 years, 2015 year-end will finally see a major updated version of PHP coming out. This version is going to be called PHP 7 rather than PHP 6. This is because the development community thought it best not to mix up things. As many of you would know that PHP 6, that was developed as an experimental project, could never see the light of the day to reach the production stage.

Meanwhile, the PHP 7 beta version, released on November 12, 2015, has been making tech discussion rounds since then. The general word is that, though this version is not production-ready, PHP 7 has taken huge strides in matters related to speed and performance. We are talking about performance leaps ranging from 25% to 70%. Word is, this can be achieved by just upgrading PHP, without the inclusion of a single line of code.

This article is aimed at answering questions you may have about what all changes and updates you can expect out of PHP 7.

The All New Zend Engine: To boost performance of PHP applications, PHP 7 makes use of the latest version of the Zend engine, code-named PHPNG (PHP Next-Gen). The Zend New Generation server attached to PHP, duly named PHPNG will double PHP’s performance. In fact, if PHP 7 lead developer & Chief Performance Engineer, Zend Technologies, Dmitry Stogov’s statement is to be believed, “PHP 7 is 14 times faster than PHP 5.0 on bench.php.”

PHP 7 twice as fast as PHP 5.6: Yes, you read that right. PHP 7 run applications will boost in performance figures as compared to those running on PHP 5.6. This is all thanks to the new PHPNG engine. Moreover, according to PHP founder Rasmus Lerdorf, the upgrade will also mean using less number of servers, while still serving the same number of users. The just-in-time compilation (JIT) is another speed catalyst, allowing run time compilation before execution.

Dependable 64-bit support: There will be no more slow data operations. 64-bit (Windows System Support) means, more physical memory to work with. Arrays and variables are more ably handled. Applications that require large data arrays will benefit, especially those concerning scientific applications, data management, digital media related and CAD-like functionality programs. Performance will be boosted ten-fold in the aforementioned programs, thanks to 64-bit.

Fatal errors to Exceptions: Grave errors have been replaced by exceptions. Engine Exceptions will allow you to revert to exceptions. This is a major and drastic improvement, considering that earlier, PHP just gave away in case of serious errors. Also, PHP 7 has brought in a shared Parent Class under \BaseException to catch two varied kind of error handling exceptions – engine and traditional exceptions.

Discarding old, unassisted SAPIs and extensions: At present, PHP is full of SAPIs connected to the servers, that are either unsupported or unavailable. Also, there are extensions with unsupported dependency libraries. The result: sizable lot of unchecked code and thus, increased security risk. That is why old SAPIs and their extensions have been removed from the source code in the latest PHP version. This will free up space and thus create room for improvements.

Anonymous Classes: Anonymous function is well-utilized, creating the scope to create anonymous class objects, especially in creating one-off objects. Support for this feature has been added in PHP 7. Used efficiently, they can hasten execution and coding time. Here is an example:

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

Return Type Declarations: This is another developer-friendly add-on. Many developers prefer declaring the function’s return type. Any type, including objects and arrays can be returned. This helps in faster function execution and passing control to the line from where it is called. Check this example out:

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

Group Use Declarations: This new feature is for those looking to use the same namespace to import several classes. The code is comparatively neat and saves you big on typing time. Debugging codes will also get easier, thanks to group use declarations helping you in identifying imports that are part of the same module. This example illustrates the use:

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

Scalar Type Declarations: Scalar type hints is a new feature inclusion, making the use of strings, floats, integers as type hints for methods and functions. Non-restrictive by default, scalar type hints will allow float value to integer parameter, just coerce it to int without any error or warning generation. Scalar Type Hints is already present in C, C++ and Java, now makes its debut in PHP 7.

 // Coercive mode
function sumOfInts(int ...$ints)
{
    return array_sum($ints);
}

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

Null Coalescing and Spaceship Operator: Two new operators are an integral part of PHP 7, the null coalesce operator and spaceship. The functionality of the spaceship operator, officially called the Combined Comparison Operator can be availed to make the chained comparison more compact. The former, apart from other functions, is used as a common use case shortcut. This is a conditional attribution, to check the set value before usage.
Programmers will enjoy greater flexibility, thanks to the JIT (just in time) compiler. PHP 7 is twice as fast to PHP 5, minus a JIT compiler. The latest PHP version is even more faster with a JIT compiler. The following illustrates the use of the null coalesce operator.

 // Pre PHP 7 code
$route = isset($_GET['route']) ? $_GET['route'] : 'index';

// PHP 7+ code
$route = $_GET['route'] ?? 'index';

Here is an example of how spaceship operator or Combined Comparison Operator works:

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

Remember, the November 12, 2015 released PHP 7 version is not production-ready yet. Yes, you can test your application with this version and report errors, that the final version can be improved on. This would certainly be time well spent. Meanwhile, we are keeping our fingers crossed on PHP 7’s final release version.

Dec 8, 2015 Update: PHP 7 was released on Dec 3, 2015. PHP 7.0.1 was released on Dec  17, 2015.

(With code inputs and guidance by Rahul Palake, Cuelogic)