PHP is by far, the most preferred programming language. But is PHP 7 the most exciting releases of them all? Yes. The whole PHP community and the people linked to PHP, are all excited to welcome the biggest release for PHP in decades. It surely adds more versatility to the already versatile language.
But you must be wondering why PHP named its latest release PHP 7 and not PHP 6. Reason behind it is that, many of the PHP 6 releases were already implemented in PHP 5.3 and later, there was not really a proper reason just to change the name. What I am trying to say here is that we haven’t missed anything. Just to avoid the confusion with a dead project, PHP's latest release was named to PHP 7.
Is This Hype Valid for PHP 7? What It Actually Brings Forth for the Developers?Hop on and let’s take a deeper dive. Let's check out what new features PHP 7 has to offer. And what improvements those features will bring forth.
The developers for the PHP 7 has done a pretty commendable job here. Now your PHP codebase uses less memory and gives you even more performance than before. After it’s release, internet was overloaded with benchmarks which were really promising. It is almost a 2x increase inserver response times with PHP 7. For further details on benchmarks click here.
The type declaration is used to specify the type of variable. PHP sets this automatically and because of which, PHP is a weakly typed language. PHP does not need you to declare the data type. Because of which, you could do radical things with the variables, like adding Float into String without resulting in an error. Type declaration helps you get the expected results. Making sure that only certain procedures can occur. Which makes the code understandable.
In the previous PHP versions, we could use type hinting method. This method specifies the type of an argument declaration in a function. But the issue with this method was that you can only use it with a function declaration. Which limits to only two types, a class name, and an array.
Scalar Type Declaration
PHP 7 has now added Scalar type declaration for int, float, string, and boolean. Adding scalar type declaration and enabling strict requirements ensures that more correct and well-documented PHP programs can be written. It also helps you in gaining more control over your code and make the code easier to read.
By default, on PHP 7, these declarations are non-strict. Which means that the type forging is possible. As if you pass a string starting with a number into a float type function, it grabs the number from in the start and skips everything else. Passing a float into a function that requires an int, that float will become int.
Non-Strict Example
function getSum(float $a, float $b) {
return $a + $b;
}
getSum(6, "7 week");
//Here int(6) changed to float(6.0) and string “7 week†changed to float(7.0)
//with a “Notice: A non well formed numeric value encounteredâ€
//returns float(13)
getSum(1.1, "2.2");
//Here string "2.2" is changed to float(2.2) without any notice
//returns float(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)
Here the getSum function receives 2 floats and adds them together returning the sum. When you use a non-strict type declaration in PHP 7. It will reforge these arguments to match the type specified in the function. Which means whatever the argument we pass, PHP will convert it to float.
Strict Example
PHP 7 additionally gives us the opportunity to strict the declaration type. It is achieved by adding “strict_types=1†on the very first line of the file. This ensures that any calls made to the functions specified must strictly adhere to the specified types. Strict is determined in the file in which the call to a function is made and not the file in which the function is defined.
While using a strict type-declaration, if a mismatch occurs, a “Fatal Error†occurs and we know that something is not functioning as desired. This helps in not causing random and confusing diagnose issues. Let's just cut the talk and take a look at an example with strict types turned on.
declare(strict_types=1);
function getSum(float $a, float $b) {
return $a + $b;
}
getSum(3, "2 week");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(1.8, "4.5");
// Fatal error: Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string given
getSum(3.1, 2);
// int(2) change to float(2.0)
//returns float(5.1)
Setting “declare strict_type†to “1â€, the first two calls that pass a string produces a Fatal error: “Uncaught TypeError: Argument 2 passed to getSum() must be of the type float, string givenâ€. With only the exception in the third call, in which if you pass an integer for an argument instead of a float value, PHP will perform “wideningâ€, which includes adding .0 at the end of the integer value. This returns (5.1).
Return Type Declarations
The third type of declaration that PHP 7 supports are a Return Type Declaration. It supports all similar type arguments as a return. Take look at the example of how to specify a return type declaration.
function getSum(float $a, float $b) : float {
}
Adding a return type ensures that only an expected value type returns. For the previous two examples if we set the return type float it will work the same. As the values being returned are already float. So we will be doing an example for int. return types.
Non-Strict Integer Example
Without the strict type declaration on, if we specify the return type as int for the previous examples, it will work the same. With just the difference being, that return will be forged to an integer. Which means it will truncate the float value and only returns the integer.
function getSum(float $a, float $b) : int {
return $a + $b;
}
getSum(6, "7 week");
// changes int(6) to float(6.0) & string(“7 weekâ€) to float(7.0)
// returns int(13);
getSum(1.1, "2.2");
// changes string "2.2" to float(2.2)
// returns int(3.3)
getSum(3.1, 2);
// changes int(2) to float(2.0)
// returns int(5.1)
Strict Integer Example
If we turn strict types on, we’ll get a Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned. For this case we’ll be casting our return value as an int. which then returns the truncated value.
declare(strict_types=1);
function getSum(float $a, float $b) : int {
// return $a + $b;
// The above statement shows Fatal error: Uncaught TypeError: Return value of getSum() must be of the type integer, float returned
return (int)($a + $b); // truncate float like non-strict
}
getSum(3.1, 2); // changes int(2) to float(2.0) and returns int(5.1)
Benefits
These new implementations of Type Declaration certainly help in making the code easier to read. With PHP 7 you get a versatile type declaration methods which makes your life easier. You can even see at the start of the function, what is required and what will be returned.
The next new feature we will be discussing are the new Error Handling techniques implemented in PHP 7. Handling fatal errors was a nightmare in previous versions of PHP. If a fatal error occurs it just simply stops the script rather than invoking the error handler. On a production server, this returns a blank white screen to your users, which in the end causes your credibility to drop.
But PHP 7 allows an exception to be thrown when an error occurs, rather than stopping the whole script. This doesn’t mean that Fatal errors are gone from PHP 7. They still exist i.e., an uncaught exception will still be a fatal error in PHP 7. One more thing to highlight here is that 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.
PHP 7 also brings us some new operators. Let’s just cut the talk and directly go through all the new operators.
Spaceship Operator
The first one in our list is the Spaceship Operator, also known as the Combined Comparison Operator. It is put together using three of the previous operators, namely, “<â€, “=†and “>â€. It looks something like this:
<=>
What this operator is useful for is that it will compare the value on the left to the value on the right and returns 3 different values. See the example below for further understanding.
$compareResult = $a <=> $b
if $a < $b it returns “-1†to the variable “compareResultâ€
if $a = $b it returns “0†to the variable “compareResultâ€
if $a > $b it returns “1†to the variable “compareResultâ€
A very useful operator. The most common use of this operator will be in sorting.
Null Coalesce Operator
Another new operator in PHP 7 is the Null Coalesce Operator. If it is not null it returns the left operand, otherwise, it returns the right operand. The thing worth mentioning here is that it won’t pop any notice if the left operand is a null variable.
$user = $userName ?? "v3ron";
In the above example, if the variable userName is not null, it will push that value to the variable “userâ€, or else “v3ron†will be assigned to the variable “userâ€.
Before PHP 7, something like this would be written as:
$user = isset($userName) ? $userName : 'v3ron';
And yes, these can be stacked which makes it much likely to be used. It will check each item from left to right until it finds one that is not null, it will use that value. For example:
The CSPRNG abbreviated as Cryptographically Secure Pseudo-Random Number Generator is an easy to use API. It provides an easy and reliable way to generate secure random integers and bytes for use within cryptographic contexts. It can be used especially for generating random passwords or password salt.
2 new functions have been introduced in PHP 7 to use namely, random_int and random_bytes. Let's analyze a bit more to see what these two brings to the table for the developers.
Random Bytes
With random_bytes, you only supply a single argument that is the length of the random string which it will return in bytes. Take a look at the example for a better understanding.
$randomByte = random_bytes(10); // 10 is the length in bytes
var_dump(bin2hex($randomByte));
// output for the above code is: string(20) "5f655db3ae43c256937b"
These are bytes, not integers. For a random number or integer, you should use the random_int function.
Random Integers
This function generates secure random integers. When using random_int you supply two arguments, that are min and max. Which tells the minimum and maximum numbers for the random integer.
For example:
random_int(2,10);
So much for all the new features. There are some features that have been removed in PHP 7, you can check them out by going to the deprecated features section in PHP 7.
Versions released before 5.5 are not compatible any longer. Now it is for you 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.