PHP 7 is kind of super major release of PHP programming language and is considered to be a revolution in the way web applications can be developed and delivered. PHP 7 release is considered to be the most important change for PHP after the release of PHP 5.
Performance & Speed
The most easily recognizable advantage of the new PHPNG engine is the significant performance improvement. The development team of PHPNG refactored (Improved by reorganising its internal structure without altering its external behaviour) the Zend Engine, and optimized memory usage in a remarkable way. The results? You can see the performance benchmarks provided by the Zend Performance Team below. Using PHP 7 executes your code faster as well as you will also need only fewer servers to serve the same amount of users.
New Operators
Spaceship Operator
PHP 7 also brings us some new operators. The first one we’re going to explore is the spaceship operator. The name itself has an attraction, who doesn’t want to use it? The spaceship operator, or Combined Comparison Operator, is good addition to the language, complementing the greater-than and less-than operators.
Example:
$myCompare = 2 <=> 1 2 < 1? will return -1 2 = 1? will return 0 2 > 1? will return 1
The spaceship operator is put together(combined with) using three individual operators, less than, equal, and greater than. Essentially what it does is check the each operator individually. First we have less than, If the value on the left side is less than the value on the right side, the spaceship operator will return -1. If not, it will move on to test if the value on the left is EQUAL to the value on the right(both equal). If so, it will return 0. If not then finally it will move on to the final test. If the value on the left is GREATER THAN the value on the right. Which, if the other 2 haven’t passed, this one must be true. And it will return 1.
Null Coalesce Operator
The Null Coalescing operator is denoted with two question marks ( ?? ). You can use it when you want to check if something exists and you need to return a default value, in case it doesn’t. The coalesce operator returns the result of its first operand if it exists and is not null, and the second operand in any other cases.
Example:
<?php // $varA is not set $varB = 20; echo $varA ?? 5; // outputs 5 echo $varA ?? $varB ?? 8; // outputs 20 ?>
Type Declarations
It has simply meaning, giving type to variable instead of allowing PHP to set automatically.
Scalar type declarations
Scalar type declaration has two options −
- coercive – coercive is default mode and hence there is no need be specified.
- strict – strict mode has to explicitly hinted.
The above modes do allow following types for function parameters −
- int
- float
- bool
- string
- interfaces
- array
- callable
Coercive Mode Example:
<?php // Coercive mode function mySum(int ...$ints) { return array_of_sum($ints); } print(mySum(1, '2', 3.2)); ?>
Output: 6
Strict Mode Example:
<?php // Strict mode declare(strict_types=1); function mySum(int ...$ints) { return array_of_sum($ints); } print(mySum(2, '3', 4.1)); ?>
Output: Fatal error: Uncaught TypeError: Argument 2 passed to mySum() must be of the type integer, string given.
Return type
Return type declaration specifies the type of value that a function should return. Following types for return types can be declared.
- int
- float
- bool
- string
- interfaces
- array
- Callable
Valid Return Type Example:
<?php declare(strict_types = 1); function returnMyIntValue(int $myValue): int { return $myValue; } print(returnMyIntValue(8)); ?>
Output: 5
Invalid Return Type Example:
<?php declare(strict_types = 1); function returnMyIntValue(int $myValue): int { return $myValue + 1.0; } print(returnMyIntValue(5)); ?>
Output: Fatal error: Uncaught TypeError: Return value of returnMyIntValue() must be of the type integer, float returned.
CSPRNG
CSPRNG stands for ‘Cryptographically Secure Pseudo-Random Number Generator’. In cryptography, we require random numbers, in the case of salts, nonce, key generation, one-time pads in certain signature schemes, etc. Hence, CSPRNG is named after this phenomenon.
PHP 7 has two new functions, which are used to generate cryptographically secure pseudo-random integers and strings in a cross-platform method. These functions are as follows.
random_bytes ()
The use of this function is to generate an arbitrary-length string of cryptographically secure pseudo-random bytes. These bytes has only cryptographic use like when we generate keys or initialize vectors as discussed before. Following is the syntax for this function.
Syntax
string random_bytes ( int $myLength ); // where $myLength = number of length
- Parameter – The function accepts the length of the string as an input parameter. It is of integer type and given in terms of number of bytes.
- Return Value – The function returns a string value which is cryptographically secure random bytes.
- Errors/Exceptions – Exceptions or errors will be thrown by the function in the following scenarios.
- If no source of randomness is found then an exception will be thrown.
- A TypeError will be thrown when input parameters are invalid.
- An error will be thrown when input parameter is passed which has an invalid length.
Example:
In the below example, we are going to generate a random string of length 10 bytes.
<?php $myBytes = random_bytes(10); print(bin2hex($myBytes)); ?>
Output: 2a58cdaf2117aee1f00a
random_int ()
This function is used to generate cryptographically secure pseudo-random integers. These integers are only used when the unbiased results are critical. Following is the syntax for this function.
Syntax
int random_int ( int $min , int $max );
- Parameters – The function accepts two input parameters ‘$min’ and ‘$max’. Both of these parameters accept integer values.
- As the name suggests ‘$min’ is the lowest value that is to be returned which could be either PHP_INT_MIN or higher.
- On the other hand ‘$max’ is the highest value that to be returned which could be, either less than or equal to PHP_INT_MAX.
- Return Value – The function returns an integer value which is a cryptographically secure random integer. This integer value will always be between the min and max range that were given as input parameters.
- Errors/Exceptions – Exception or error will be thrown by the function in the following scenarios.
- If no source of randomness is found then an exception will be thrown.
- A TypeError will be thrown when input parameters are invalid.
- An error will be thrown when the value of ‘$max’ is given less than the value of ‘$min’ as input parameters.
Example:
<?php print(random_int(50, 1000)); print(""); print(random_int(-1000, 0)); ?>
Output:
116
-647
Anonymous Classes
Anonymous classes can now be defined using new class. Anonymous class can be used in place of a full class definition.
<?php interface MyLogger { public function myLog(string $msg); } class MyApplication { private $myLogger; public function getMyLogger(): MyLogger { return $this->myLogger; } public function setMyLogger(MyLogger $myLogger) { $this->myLogger = $myLogger; } } $myApp = new MyApplication; $myApp->setMyLogger(new class implements MyLogger { public function myLog(string $myMsg) { print($myMsg); } }); $myApp->getMyLogger()->myLog("Anonymous Classes Example"); ?>
Output: Anonymous Classes Example