Everything you wanted to know about PHP 7

Everything you wanted to know about PHP 7

By | June 6th, 2016
No Comments on Everything you wanted to know about PHP 7

The omnipresent PHP moved to version 7 directly from version 5. The update

came out in December and we’ve allowed more than enough time for the

initial set of kinks to be ironed out. Here’s what you need to know


														
							

As per W3Techs, of all the websites in the world whose server side language is known, PHP powers 82.2% of the websites. Of these 82.2%, 80.72% of the websites are using PHP 5. The best of the CMS (Content Management System) available today – be it WordPress, Joomla, Drupal or Magento are all built with PHP. PHP 5 was released back in 2004 and since then minor releases kept on adding many exciting features to PHP, including support of OOP (Object-Oriented programming) and many other features associated with that. Until recently, the latest stable release version of PHP was 5.6 which was released in mid-2014.

php

Recently, the PHP community marked the release of its latest version – PHP 7. This new version of PHP brings along with it – dynamic performance improvements, minimal memory consumption, and a series of unparalleled language features to let you take your app to the next level. PHP 7 has brought along with it the all new Zend Engine 3.0 (not Zend Framework!). In comparison to PHP 5.6, apps built with PHP 7 turn out to be twice as fast in performance and consume 50 per cent less memory. Thus, you can now serve more users concurrently, without upgrading your hardware. All thanks to Zend Engine. Aren’t we already in love with it?

But why PHP 7, not PHP 6? Well, things didn’t turn out very good with Unicode. The PHP fraternity previously had goals to release a new major version back in 2005. The new version was supposed to implement Unicode and a whole lot of other features. Most of those other new features were added in the subsequent PHP version 5.3 and later, except the Unicode. In the meanwhile, PHP 6 always existed as an experimental project and a lot was talked and published about it, but it could never make it up to the production phase. Thus, considering the name as PHP 7 was always a viable option to avoid confusion and hindrance to the mass regarding the contents and features of the newest version.

performance

Performance improvement with PHP7

A lot being already discussed about the basic advantages and naming pattern, it’s time we look into the new features and functionalities that PHP 7 brings along with it.

1. New Operators

Finally, PHP brings in two new operators and these operators are definitely going to make your life much easier.

The Spaceship Operator (<=>)

This operator goes by the official name of Combined Comparison Operator. The notation of this operator looks kind of like a spaceship (if you have ever seen one). The spaceship operator is built up by combining three different operators – less than, equal, and greater than. Although, these operators are combined together, each of these operators is checked individually from left to right.

left <=> right

Consider the above line of PHP code which uses the spaceship operator –

engine

a) If the left value is less than the value the right value, the operator will return -1.
b) If the left value is equal to the value the right value, the operator will return 0.
c) If the left value is greater than the value the right value, the operator will return 1.

Note: If you were to do the same in PHP version 5.6 or below, we would have to write the following piece of code –

left < right? return -1
left = right? return 0
left > right? return 1

Null Coalesce Operator (??)

If you have even tried learning PHP, there is no way you wouldn’t have come across the isset() function and later you might have also realized that using this function repeatedly to check if a value is set or null is way too old school. The Null Coalesce Operator brings an alternative to isset() function. It provides us with a shorthand alternate to what isset() does with inline comparison.

$source = $defined ?? “Undefined”;

Consider the above line of PHP code which uses the null coalesce operator. The above line of code first checks if the variable defined is set or null. If defined is set, it will assign its value to the variable source. If variable defined is not set i.e. null, it will assign “Undefined” to the variable source.

Note: If you were to do the same in PHP version 5.6 or below, we would have to write the following piece of code –
if (!empty($defined))
$source = $defined;
else
$source = “Undefined”;
Shouldn’t you be thanking PHP 7, already?

2. Awesome Error Handling

In PHP 5.6 or below, error handling was such a pain. In case there was a fatal error, the framework wouldn’t even invoke the error handler and consequently stop the script from processing. Thus, the white screen of incredibility. Well, gone are the bad days. In PHP 7, if there is a recoverable or fatal error, an exception will be thrown. Yes, no more white screens. Fatal errors also include errors such as running out of memory and an uncaught exception. In PHP 7, Errors and Exceptions work pretty much in a similar way. Both implement the Throwable class. Yes, that means that now you can use Throwable in try/catch blocks for both Errors and Exceptions. However, in PHP 7 for Error, we now have some more specific error – AssertionError, ArithmeticError, Divison- ByZeroError, TypeError and ParseError.

Consider the line of PHP code below as an example which uses
Throwable to handle Errors and Exceptions –

//Error as Throwable
try {
someFuntion();
} catch (Throwable $t) {
echo “Throwable: “.$t->getMessage().PHP_EOL;
}
//Exception as Throwable
try {
throw new Exception(“Something”);
} catch (Throwable $t) {
echo “Throwable:
“.$t->getMessage().PHP_EOL;
}

3. Accurate Type Declarations

PHP has always been a weak typed language. It has never been mandatory to declare the type of variable; PHP would get it done for you by itself based on the value you assigned. But, at times, this would also result in some unintended and unexpected return values. To overcome this scenario, PHP 7 brings in Type Declarations so that you ca specify the type of variable being set instead of depending on PHP to set it automatically for you. PHP 7 has added two types of declarations for this purpose – Scalar Type Declarations and Return Type Declarations.

Scalar Type Declarations

Scalar Type Declarations comes in two forms – coercive and strict. Scalar types are available in four flavors – int, float, string, and bool. Scalar type-declarations, by default, are coercive. In case of coercive, PHP would change the original type of variable to match the one specified by the type-declaration, by itself. This gives you, as a developer, less control over your code and can make the code difficult to understand.

function sum(float $a, float $b) {
return $a + $b;
}
sum(2, “1abc”);

Consider the above line of PHP code which uses coercive scalar type declaration. What would you expect the sum method to return? Go ahead, try this piece of code and you will be amazed with the result returned. Because, it is coercive, PHP would change int(2) to float(2.0) and string “1abc” to float(1.0) and return a certain notice. The sum method would return float(3) as the output.

You can overcome this situation in PHP 7, with strict scalar type declaration. Strict mode is enabled on per-file basis by a single declare directive at the top of the file.

declare(strict_types=1);

Note that, this directive would also affect the function’s return type.

declare(strict_types=1);
function sum(float $a, float $b) {
return $a + $b;
}
sum(2, “1abc”);

Consider the above line of PHP code which uses strict scalar type declaration. In the above piece of code, for the first parameter PHP will widen the int variable by adding a .0 after the int and for the second parameter PHP will produce a Fatal error: Uncaught TypeError: Argument 2 passed to sum() must be of the type float, string given.

Return Type Declaration

Like Scalar type, Return Type Declaration also comes in two forms – coercive and strict. Return type declaration lets you specify the type of value which will be returned. In the coercive mode, returned values will be modified to the correct type. In strict mode, if the returned value is not of the correct type, it shall throw a TypeError.

function sum(float $a, float $b) : float {
return $a + $b;
}
sum(2,1);

The above piece of code is in coercive mode and note that though the parameters passed to the sum method are of int type, PHP would modify the values to return the result in float type.

declare(strict_types=1);
function sum(float
$a, float $b) : float {
return $a + $b;
}
sum(2,1);

This piece of code is in strict mode and note that because the parameters passed to the sum method are of int type and the expected type is float, PHP would return you with Fatal error: Uncaught TypeError: Return value of sum() must be of the type float, integer returned.

4. Adds Anonymous Class

Other languages in the league of PHP, like C# and Java already had a big support and usage of Anonymous classes. PHP introduced the concept of Anonymous Classes with its latest edition.

Anonymous classes are basically classes without names. These are generally used in scenarios where you need to use a class just once during execution or don’t need the class to be documented. The object instantiation for an Anonymous class is same as instantiating an object for a names class. However, the best part about Anonymous classes is that you can instantiate an object and define a class in a single line.

$bar = new class {
public function bar() {
return “foo”;
}
};
var_dump($bar,$ bar -> bar ());

5. The Integer Division Function

The Integer Division ( intdiv ) function is not much of a significant addition, however worth mentioning. This method promises to return an int value always, for all the division operations performed. A regular division operation generally leads to a float result being returned. So earlier, in case, if you had to round off your result to get the int value…this method is a life saviour for you.

var_dump (intdiv (4,3),(4/3) );

This piece of code would return 1 instead of 1.34.

6. Enhanced CSPRNG Functions

CSPRNG stands for Cryptographically Secure Pseudo Random Number Generator. PHP 7 has brought in a set of CSPRNG to generate random numbers in a secure way. Though, PHP already had methods like rand() to generate random data, but these methods weren’t secure. In PHP 7, a system interface is tied along with the operating system’s random data generator and because of this the security of the random data generated through PHP is as secured as the operating system. This can be very useful in case of random passwords and salts. CSPRNG introduces two new functions – random_int and random_bytes.

random_int

The random_int method basically returns a random number between a maximum and minimum range specified by the user.

Consider the example below –
random_int(15,20);

The above piece of code would generate a random number between 15 and 20, including the number 15 and 20.
random_bytes

The random_bytes method returns random byte (generally string) of a length specified by the user. Consider the example below – random_bytes(5);
The above piece of code would generate a random byte of length 5.

7. Import from the same namespace

PHP 7 has brought along with it another great new feature – Group use Declaration. This feature is a bliss for all those who want to import multiple classes from the same namespace. The new features cut out wordiness, and lets you import same namespace classes inline, thus making your code look cleaner.

Use lib\namespaceA\{ClassA, ClassB, ClassC as C};

Consider the above line of PHP code which uses the Group use Declaration. The above line of code declares ClassA, ClassB and ClassC which belong to same namespace namespaceA in a single line of code.

Note: If you were to do the same in PHP version 5.6 or below, we would have to write the following piece of code –

use lib\namespaceA\ClassA;
use lib\namespaceA\ClassB;
use lib\namespaceA\ClassC as C;

Move on to PHP 7

PHP 7 looks very promising. There are a lot of other features added in PHP 7 like Unicode support for international characters and emoji too! The performance improvement is tremendous and the security enhancement is remarkable. There are also a lot of features which have been removed in PHP 7. However, these features where already deprecated since PHP 5, so maybe you weren’t using them at all. If your site is built using WordPress, there is a good news for you. WordPress Core is already getting ready for PHP 7. So, its high time you started considering upgrading your servers to PHP 7 for better performance and an easier life.

Google
Nash David
Nash David is passionate about technology and mobile devices. He closely follows the smartphone, and tablet platform market. He also leads editorial efforts for devworx. You may send him tweets @nashpd or email editor@devworx.in
@
  • IBM, TCS, HCL, LTI & More Top IT Companies are Hiring
    Sign Up, Search & Apply for Latest Job Vacancies with Monster to Get Placed in Top IT Companies. Get The Right Job for Your Career, Log onto www.monsterindia.com
    Click to know more