New Features introduced in PHP 7

New Features introduced in PHP 7
New Features introduced in PHP 7

With the release of PHP 7 on Dec 3rd, 2015 in the PHPs ecosystem, many new features introduced in PHP 7 version. This version actually brought an evolutionary change in the release that provided many new features and boosted performance to a new level.

In broader way, here are the list of New Features introduced in PHP 7-
  • Major Performance upgrade.
  • Scalar type declarations.
  • Return type declarations
  • Null coalescing operator
  • Spaceship operator
  • Constant arrays using define()
  • Anonymous classes
  • Group use declarations

Above are the some of the new features added in the PHP 7. We’ll see all the above features one by one and we’ll also see deprecated features as well.

1. Major Performance UPgrade

It’s all about memory management. Lesser the memory consumption faster will be the execution time.

PHP 7 has come up with the PHPNG engine that speeds up PHP applications more than the previous PHP version i.e. v5 & also 50% better memory consumption than PHP 5.6. This means now the server can returns pages to users twice as fast. With this, we not only saving a burden on the servers but also increases the traffic by serving twice customers at the same speed as they did before.

What is PHPNG?

PHPNG stands for PHP Next Generation.

So, whenever we add new features/fix any bug then for that purpose we create a new branch for maintainability. So that if because of that branch any issue occurred then we can only focus that branch and fix the issue. In the worst-case scenario, removed that branch from the master.

PHPNG is also referred to as a new branch to the PHP project which aims to bring performance improvement and memory usage efficiency to PHP.

PHPNG implements JIT (Just In Time) dynamic compilation of PHP code to the native machine to achieve speed improvements.FYI- PHPNG is NOT a JIT.
This upgrade focused mainly on rewriting Zend Engine core parts to enable optimized memory allocation to the PHP’s data types.

2. Scalar type declarations

Before jumping into big topic, lets understand about strict types-

PHP strict Types

PHP has always been a weakly typed language, means If we pass the value “1” to the function which has been declared as int in the function declaration then PHP interpreter will accept it as an integer itself and not throw any errors because PHP will internally typecast it into an integer.

<?php

function getId(int $id) {
    return $id;
}

echo getId('123');
// OUTPUT

123

To enable strict mode, a single declare directive must be placed before the the function.

<?php

declare(strict_mode = 1);

function getId(int $id) {
    return $id;
}

echo getId('123');

Note, different PHP versions will give different errors

// OUTPUT

5.0.0 - 5.0.5
Fatal error: Argument 1 must be an object of class int in file.php on line 5

5.1.0 - 5.1.6
Fatal error: Argument 1 passed to getId() must be an object of class int, called in file.php on line 9 and defined in file.php on line 5

5.2.0 - 5.2.17
Catchable fatal error: Argument 1 passed to getId() must be an instance of int, string given, called in file.php on line 9 and defined in file.php on line 5

5.3.0 - 5.6.40
0Warning: Unsupported declare 'strict_types' in file.php on line 3 Catchable fatal error: Argument 1 passed to getId() must be an instance of int, string given, called in file.php on line 9 and defined in file.php on line 5

Output for 7.0.0 - 7.2.31
Fatal error: Uncaught TypeError: Argument 1 passed to getId() must be of the type integer, string given, called in file.php on line 9 and defined in file.php:5

Output for 7.3.0 - 7.4.7
Fatal error: Uncaught TypeError: Argument 1 passed to getId() must be of the type int, string given, called in file.php on line 9 and defined in file.php:5

Now, let’s jump right into our main topic Scalar type declaration in PHP.

Before PHP 7, four types of type declaration were allowed to pass as an argument. class names/self, interfacesarray, and callable.

With the release of PHP 7, now we can pass strings (string), integers (int), floating-point numbers (float), and booleans (bool) as an argument in the function as seen in the above example.

3. Return type declarations

In addition to argument type declaration (seen above), PHP has introduced a return type declaration in the 7.0 version. In this, we can mention inside the function declaration that which return type we are expecting from the function.

This means once defined and function failed to return that return type then PHP will throw Fatal Error.

<?php

class foo {
    
    public $id = 2;
    
}

function getId(foo $obj): foo {
    return $obj;
}

print_r(getId(new foo));
// OUTPUT

foo Object 
( 
    [id] => 2 
)

So, if we pass different class name in the parameter list then PHP will throw critical error

Fatal error: Uncaught TypeError: getId(): Return value must be of type bar, foo returned in file.php:12

Note that- We did not declare strict type above the function call. So we do not require to mention it explicitly. PHP will interpret it internally.

4. Null coalescing operator

Null coalescing operator already explains the previous post. But let’s rewind it here once again.

In extend to Ternary Operator, the null coalescing operator “??” is available as of PHP 7.0.0

As compared to Ternary Operator, in Null Coalescing Operator, the expression1 ?? expression2 evaluates to expression1 if expression1 is not NULL, otherwise expression2.

Basically Null Coalescing Operator works same like isset() function which evaluates all values to true except following

  • $y = null;
  • var $y;
  • $y is undefined

For more details refer this comparison of variable with PHP functions table.

<?php

// Null Coalesce Operator Example
$result = $action ?? 'default';

// The above is very identical to this if else statement
if (isset($action )) {
    $result = $action;
} else {
    $result = 'default';
}
?>

In the above example, if the $action is not defined then it will not generate any PHP Notice Error but rather it will return false and hence the output of the first statement is default

5. Spaceship Operator

Well, this new operator name looks weird but yes it has many advantages in the context of comparing two expressions. It returns -1, 0, or 1 when Left side Expression is respectively less than, equal to, or greater than Right Side Expression.

<?php

// Integers
echo 1 <=> 1; // 0
echo 1 <=> 2; // -1
echo 2 <=> 1; // 1

So, in the codebase we can use it like this-

<?php

function compare_values($a, $b) {

    switch($a <=> $b) {
        case 1:
            echo "$a is greater than $b".PHP_EOL;
        break;    
        case 0:
            echo "$a is equal to $b".PHP_EOL;
        break;
        case -1:
            echo "$a is less than $b".PHP_EOL;
        break;
    }
}

compare_values(1, 2);
compare_values(1, 1);
compare_values(1, 0);
// OUTPUT

1 is less than 2 
1 is equal to 1 
1 is greater than 0

6. Constant arrays using define()

Now we can use Array constants using define(). Prior to this, it was possible in PHP 5.6 with const. We can use numeric, associative & multidimensional array.

<?php

// numeric array
define('AVENGERS', [
    'CAPTAIN AMERICA',
    'IRON MAN',
    'THOR',
    'HULK'
]);

echo AVENGERS[3]; // outputs "HULK"
?>
<?php

// associative array
define('AVENGERS', [
    ['GOD' => 'THOR'],
    ['TECH' => 'IRON MAN'],
    ['SOLDIER' => 'CAPTAIN AMERICA'],
    ['SCIENTIST' => 'HULK']
]);

echo AVENGERS[3]['SCIENTIST']; // outputs "HULK"
?>

7. Anonymous Classes

In the previous post, we learned about closure/lambda function in which we defined an anonymous function and assigned it to either a variable OR passed as a parameter in the callback functions.

new class{};

This is the basic syntax of anonymous class. We can define variable and methods inside it.

Let’s understand it using regular class definition and how anonymous class is different from it.

<?php
class event {
    
    public $id = 2;
    
    public function getId() {
      return $this->id;
  }
}

class home {
  public function getEventId(event $eventObj) {
    echo $eventObj->getId();
  }
}

(new home)->getEventId(new event);

With anonymous class:

<?php

class event {
    
    public $id = 2;
    
    public function getId() {
      return $this->id;
  }
}

$objAnonymous = new class {
   public function getEventId(event $eventObj) {
    return $eventObj->getId();
  }
};

print_r($objAnonymous->getEventId(new event));

As we can see anonymous classes are the classes without name. It comes as a savior at the place where we do want to create a separate class for a small piece of work. We can now anonymous class where we can pass whatever we wish to like the regular class.

Advantages:

  • can take constructor as an argument(s)
  • implement interfaces
  • extend other classes, and
  • use traits

8. Group use declarations

In the previous post (Understanding namespace in PHP), we have learned how can we use the namespace keyword in PHP.

With the release of PHP 7, namespace has been improved with combining multiple namespaces into single declaration.

As we know, we can access classes, functions and constants that can be accessed via namespace. Now we can combine them in the single-use statement.

<?php
// Before PHP 7
// class
use src\folder\namespace\Class_A;
use src\folder\namespace\Class_B as B;

// function
use function src\folder\namespace\fn_A;

// constant
use const src\folder\namespace\Const_A;

// With PHP 7
use src\folder\namespace\{Class_A, Class_B as B};
use function src\folder\namespace\{fn_A};
use const src\folder\namespace\{Const_A};
?>

Conclusion:

With the release of PHP7, we can say that PHP is now really getting matured day by day and with the introduction of new features and removing not required ones can bring new heights in the PHP ecosystem.