PHP 7 New Features and Enhancements Explained

Last Updated: 13 Feb, 2023

In this tutorial, we are going to learn about PHP 7 and its most important features and enhancements. PHP 7 was released in December 2015 (3rd Dec 2015). It was a major release and considered to be the most important release of PHP. PHP 7 came up with lots of new features that changed the way of web applications development.

Below are the list of important and new features fo PHP 7:

1. Improved Performance and Reduced Memory Consumption

PHP 7 is extremely fast as compared to PHP 5. PHP 5 was using very old version of Zend engine called ZEND II and its performance, in terms of speed, was very slow compared to PHP 7. PHP 7 came up with a brand new model of super fast engine called PHPNG (also known as PHP Next Generation). PHPNG is a brand new approach that is based on refactored Zend Engine. PHPNG has increased the websites speed and offers better performance and efficient memory usage to PHP.

2. Introduced Scalar type declarations

PHP 7 has introduced a new feature called Scalar Type Declarations which offers two options COERCIVE and STRICT.

COERCIVE - this is default mode and you no need to specify it explicitly.
STRICT - this mode you have to specify explicitly if required.

You can apply these mode on the scalar types (int, float, bool, string, array, interface, callable) of function parameters.

COERCIVE Mode Example:

<?php
/* coercive mode */
function calculateProduct(int ...$numbers) {
    $product = array_product($numbers);
    return $product;
}
$numbers = [1, 2, 3.5];
$p = calculateProduct(...$numbers);
echo "Product of the numbers ".implode(', ', $numbers)." is: ", $p, PHP_EOL;
?>

=== OUTPUT ===

Product of the numbers 1, 2, 3.5 is: 6

STRICT Mode Example:

In this mode, we must pass all the inputs of integer type to the calculateSum() function else it will throw Fatal error. You can try below example and check:

<?php
/* strict mode */
declare(strict_types = 1);
function calculateSum(int ...$numbers) {
    $sum = array_sum($numbers);
    return $sum;
}
$numbers = [1, 2, 3.5];
$sum = calculateSum(...$numbers);
echo "Sum of the numbers ".implode(', ', $numbers)." is: ", $sum, PHP_EOL;
?>

=== OUTPUT ===

PHP Fatal error:  Uncaught TypeError: Argument 3 passed to calculateSum() must be of the type int, float given ...

3. Introduced Return Type Declarations

In PHP 7, Return Type Declaration has been introduced which forces the functions that it must return specified type of value. In this way, we can write more accurate and robust code which will improvize codebase. In PHP 7, we can specify following return types for the functions:

int, float, bool, string, array, interface, and callable.

Valid Return Type Example:

<?php
/* declare strict mode */
declare(strict_types = 1);
function findSum(int $x, int $y): int {
    $sum = $x + $y;
    return $sum;
}
$x = 100; $y = 200;
$sum = findSum($x, $y);
echo "Sum of $x and $y is: ", $sum, PHP_EOL;
?>

=== OUTPUT ===

Sum of 100 and 200 is: 300

Invalid Return Type Example:

Below code example will throw an error because we have specified return type as int but the functions is returning float type of value. Look at below example code:

<?php
/* declare strict mode */
declare(strict_types = 1);
function findProduct(int $x, int $y): int {
    $product = $x * $y;
    return $product + 10.55;
}
$x = 100; $y = 200;
$p = findProduct($x, $y);
echo "Product of $x and $y is: ", $p, PHP_EOL;
?>

=== OUTPUT ===

PHP Fatal error:  Uncaught TypeError: Return value of findProduct() must be of the type int, float returned ...

4. Introduced Null Coalescing operator

PHP 7 has introduced an amazing new feature called Null Coalescing operator which is very helpful and reduced developeres work. This operator can be used to perform the same task that we used to do with ternary operator in conjunction with isset() function. This operator returns the following values:

  • First operand: if first operand exists and is not NULl
  • Second operand: if first operand does not exist or NULL

Look at the below code example:

<?php
$person = array('name' => 'Mohan');

/* Using Null Coalescing operator */
$name = $person['name'] ?? 'Not found!';
echo '===== using Null Coalescing operator ===',PHP_EOL;
echo 'Person: ', $name, PHP_EOL;

/* Using Ternary operator */
$name = isset($person['name']) ? $person['name'] : 'Not found!';
echo '===== using Ternary operator ===',PHP_EOL;
echo 'Person: ', $name, PHP_EOL;
?>

=== OUTPUT ===

===== using Null Coalescing operator ===
Person: Mohan
===== using Ternary operator ===
Person: Mohan

5. Introduced Spaceship operator (<=>)

PHP 7 has also introduced Spaceship operator (<=>) that is very helpul for the PHP developers. It helps developers to compare two expressions and returns following values:

  • 0 - It returns 0 if both expressions are EQUAL.
  • -1 - It returns -1 if first expression is LESS THAN second expression.
  • 2 - It returns 1 if first expression is GREATER THAN second expression.

Check out this code example:

<?php
$x = 100; $y = 100; $z = 200;
switch ($x <=> $y) {
    case 0: echo 'X is equal to Y'; break;
    case 1: echo 'X is greater than Y'; break;
    default: echo 'X is less than Y'; break;
}
echo PHP_EOL;
switch ($x <=> $z) {
    case 0: echo 'X is equal to Z'; break;
    case 1: echo 'X is greater than Z'; break;
    default: echo 'X is less than Z'; break;
}
echo PHP_EOL;
switch ($z <=> $y) {
    case 0: echo 'Z is equal to Y'; break;
    case 1: echo 'Z is greater than Y'; break;
    default: echo 'Z is less than Y'; break;
}
echo PHP_EOL;
?>

=== OUTPUT ===

X is equal to Y
X is less than Z
Z is greater than Y

6. Introduced CSPRNG Functions

PHP 7 has introduced new Cryptographically Secure Pseudorandom Number Generator (CSPRNG) functions. These functions are very helpful when we required to generate random data. It have introduced following two functions that are able to generate secure random strings and integers:

  • random_bytes() : Allows us to generate secure cryptographically pseudo-random bytes.
  • random_int() : Allows us to generate secure cryptographically pseudo-random integers.

random_bytes()

This function is used to generate an specified length of string of cryptographic random bytes. These strings are suitable for various cryptographic use, such as when generating secure keys or salts.

Syntax:

random_bytes(int $length): string

random_bytes() Example:

<?php
$rand_bytes = random_bytes(8);
$hex_str = bin2hex($rand_bytes);
echo 'Hexadecimal String: ', $hex_str, PHP_EOL;
?>

=== Output ===

Hexadecimal String: 290a9dc112b627b2

random_int()

This function is used to generate secure cryptographic random integers that are best suitable when results are critical.

Syntax:

random_int(int $min, int $max): int

random_int() Example:

<?php
$rand_int = random_int(100, 500);
echo 'Random Integer: ', $rand_int, PHP_EOL;

$rand_int = random_int(-100, 0);
echo 'Negative Random Integer: ', $rand_int, PHP_EOL;
?>

=== OUTPUT ===

Random Integer: 362
Negative Random Integer: -60

7. Introduced Constant Arrays

In PHP 7, you can define constant arrays with the help of define() function. Previously in PHP 5 it was only possible using const keyword.

Constant Array Example:

<?php
define('brands', [
    'toyota' => array('Innova', 'Fortuner', 'Corolla'),
    'tata' => array('Safari', 'Harier', 'Storm')
]);
echo '/***** Popular Brands *****/', PHP_EOL;
print_r(brands);
?>

=== OUTPUT ===

/***** Popular Brands *****/
Array
(
    [toyota] => Array
        (
            [0] => Innova
            [1] => Fortuner
            [2] => Corolla
        )

    [tata] => Array
        (
            [0] => Safari
            [1] => Harier
            [2] => Storm
        )

)

8. Introduced Anonymous Classes

In PHP 7, you can now easily define Anonymous Classes using new class and it can be used inline in place of full class definition. With the help of anonymous classes, you can boost the code execution to accomplish the tasks more quickly.

Anonymous class Example:

<?php
$anonymous_class = new class {
    public function sayHelloArtisans()
    {
        echo '/***** Hello from Anonymous Class *****/', PHP_EOL;
    }
};
$anonymous_class->sayHelloArtisans();
?>

=== OUTPUT ===

/***** Hello from Anonymous Class *****/

9. Introduced Closure::call()

In PHP, closures are anonymous functions which are declared inline and assigned to a desired variable and you can used it as a callback for later execution. In PHP, you can easily bind an object scope to a closure and later you can invoke it. PHP 7 has introduced Closure::call() method that simplifies this process.

Closure::call() Example:

<?php
class Animal {
    protected $name = 'Tiger';
    public function __construct($name) {
        $this->name = $name;
    }
}
$print_name = function () {
    return 'Animal Name: ' . $this->name . PHP_EOL;
};

/*** PHP 7 style ***/
$php7_animal = $print_name->call(new Animal('Elephant'));
echo $php7_animal;

/*** PHP 5 style ***/
$php5_animal = $print_name->bindTo(new Animal('Lion'), 'Animal');
echo $php5_animal();
?>

=== OUTPUT ===

Animal Name: Elephant
Animal Name: Lion

10. Introduced Group use declarations

In PHP 7, now you can use a single use statement to import Classes, Constants and Functions from the same namespace instead of writing multiple use statements.

Group use declarations Example:

<?php
/*** PHP 5 Style use statements ***/
use src\LClick\ClassX;
use src\LClick\ClassY;

use const src\LClick\ConstantX;
use const src\LClick\ConstantY;

use function src\LClick\FunctionX;
use function src\LClick\FunctionY;

/*** PHP 7 Style use statements ***/
use src\LClick\{ClassX, ClassY};
use const src\LClick\{ConstantX, ConstantY};
use function src\LClick\{FunctionX, FunctionY};
?>

11. Facilitates Fatal Errors Handling

Fatal Error handling mechanism in completely changed in PHP 7. With the new powerful Engine Exceptions, PHP 7 allows us to replace fatal errors with exceptions.

Sampel Error Handling Example:

<?php
class Product  {
    protected $name = 'Shirt';
    protected $price = 100;
    public function getNameAndPrice(): string {
        try {
            $p = $this->price % 0;
            return "Name: " . $this->name . ", Price: " . $p;
        } catch (DivisionByZeroError $e) {
            return "Error: " . $e->getMessage();
        }
    }
}
$p = new Product();
$ret_data = $p->getNameAndPrice();
echo $ret_data, PHP_EOL;
?>

=== OUTPUT ===

Error: Modulo by zero

 

Thank You, Please Share.

Recommended Posts

IMAGE

PHP OOP Interfaces Explained

An Interface allows you to create programs that specifies which methods a class must implement, without defining how those methods are implemented.

IMAGE

PHP OOP Abstract Classes Explained

A PHP class that has minimum one abstract method is called as abstract class and cannot be instantiated by itself.

IMAGE

PHP OOP Traits Explained

Traits in PHP, are a medium of implementing code reuse and allow us to reuse sets of functions freely in several independent classes.