📜 ⬆️ ⬇️

Introduction to PHP 7: What's added, what's removed

One of the most significant events that occurred in the PHP world in 2015 was the release of PHP 7. For 10 years, it was separated from the release of the first release of PHP number 5. With the increase in the first digit in the version number, there were a lot of innovations in PHP 7, increased and speed of work.
However, in the seventh version, outdated functionality was removed, which led to some problems with backward compatibility, making it difficult to transfer old applications to the new version. This article can serve as a quick guide if you are planning to write new or translate your existing PHP 7 applications.

Wait, where is PHP 6?


If you haven't worked with PHP for a while, you might wonder where PHP 6 went, why did we jump from PHP 5 to PHP 7 right away? Well, I'll be brief, the release of PHP sixth version did not take place. The main feature of version 6 was support for Unicode characters, since PHP is mainly used in web development, the Web needs Unicode support, so its implementation made sense.

The idea was to implement Unicode support directly in the kernel. This approach was supposed to expand the possibilities of the language - from using stupid emoji as the names of variables and functions, to the powerful functionality of international strings. For example, in the case when another language uses upper and lower case letters different from English or when converting a name in Chinese into a name in English.

PHP6 was ambitious, but it sucks. Therefore, we started PHP7, skipping the sixth version in the process.

Unfortunately, this ambitious plan had far more problems than expected. Most of the code base had to be ported to support Unicode, both in the case of the kernel and in the case of important extensions, which turned out to be tedious and difficult. This slowed down the process of developing other language features, which upset many PHP developers. There were other barriers, which led to a drop in interest in the development of embedded Unicode support, and over time the project turned out to be completely abandoned.
')
And since a lot of resources, such as books and articles, were written using the name of PHP 6 and Unicode support, it was decided to assign the name of the PHP 7 version - just to avoid misunderstanding.

Whatever it was, enough to dig into the dark past. Let's take a look at what's new in PHP 7.

Performance Wars, PHP 7 vs. PHP 5


Virtually all updates introduced small performance improvements. This time, however, PHP's performance, compared to earlier versions, has grown much more significantly, becoming one of the most attractive features of PHP 7. It was part of the “PHPNG” project (“php new generation” or “php new development”, - translator ), which touched the Zend Engine itself.

Refactoring the internal data structures and adding an additional step before compiling the code in the form of an abstract syntax tree - Abstract Syntax Tree (AST), led to superior performance and more efficient memory allocation. The numbers themselves look promising - tests performed on real-world applications show that PHP 7 is on average twice as fast as PHP 5.6 and also uses 50% less memory during query processing, which makes PHP 7 a strong contender for the HHVM JIT compiler from Facebook. Take a look at this Zend infographic , which displays performance for some well-known CMS and frameworks.

PHP 7 looks familiar, but it is “honed” for performance. The improved Zend Engine and the resulting performance gains have led to a huge difference between it and the previous version.

Reducing memory consumption allows weaker computers to better process requests, providing the ability to build microservices around PHP. Internal changes, in particular the implementation of AST, also opens up opportunities for future optimizations that can further increase performance. A new proprietary implementation of the JIT compiler was developed with the intention of development in future versions.

Syntactic Sugar in PHP 7


In PHP 7, there are several new syntax items. Why not expand some of the features of the language itself, if they offer a better or easier way of writing nice looking code?

Grouping import declarations


Now we can group declarations of import of classes that are in the same namespace, in one line. This will help us align the declaration with some kind of meaningful way, or just save a couple of bytes of your code.
use Framework\Module\Foo; use Framework\Module\Bar; use Framework\Module\Baz; 


In PHP 7, you can write:
 use Framework\Module\{Foo, Bar, Baz}; 


Alternatively, if you prefer a multi-line style:
 use Framework\Module{ Foo, Bar, Baz }; 


Null coalescent operator


Solves a common problem in PHP. It occurs if we want to assign a value to a variable that is assigned to another variable, but if the value of the last variable was not assigned, then assign some explicit value. Often manifested when working with user input.

Before PHP 7:
 if (isset($foo)) { $bar = $foo; } else { $bar = 'default'; //  $bar  'default'  $foo  NULL } 


In PHP 7:
 $bar = $foo ?? 'default'; 


Can be used with a chain of variables:
 $bar = $foo ?? $baz ?? 'default'; 


The operator “spaceship”


The operator “spacecraft” <=> allows a three-level comparison of two values, allowing you to understand not only their equality or inequality, but also which of them is greater with inequality, returning 1.0 or -1.

In this case, we can take different actions depending on how the values ​​differ:
 switch ($bar <=> $foo) { case 0: echo '$bar  $foo '; case -1: echo '$foo '; case 1: echo '$bar '; } 


The compared values ​​can be of type integer, float, string, and even be arrays. How do different values ​​compare with each other? See the documentation .

New in PHP 7


Of course, PHP 7 has a new, impressive functionality.

Types of scalar parameters and hints for returned types


In PHP 7, we expanded the pre-existing parameter declaration in methods (classes, interfaces, and arrays) by adding four scalar types — integer (int), float (float), boolean (bool), and string (string) as a possible parameter type.

In addition, optionally we can specify the type of result returned by a function or method. The types bool, int, float, string, array, callable, the name of the class or interface and parent (for class methods) are supported.
 class Calculator { // ,      integer public function addTwoInts(int $x, int $y): int { //  ,     return $x + $y; } } 

Declaring types will allow building transparent applications, avoiding passing and returning invalid values ​​when working with functions. Other advantages are the emergence of static code analyzers and IDEs, which offer a clearer display of the code in the absence of DocBlocks documenting notes.

Since PHP is a weakly typed language, some parameter values ​​and return types will be based on the context. If we pass the value “3” to a function that has a declared parameter of type int, the interpreter will consider it as an integer and will not generate an error. If you are not satisfied with this behavior, you can work in strict mode - strict mode - by adding the appropriate directive.
 declare(strict_types=1); 

It is set separately for each file, because the global option would divide code stores into those in which files were developed with the option enabled and those where it was disabled, which would lead to unpredictable behavior when working with code from two stores with different settings.

Engine exceptions


With the advent of kernel-level exceptions, fatal errors that previously could have stopped the execution of the script can now be easily intercepted and processed.

Errors such as calling a non-existent method will no longer stop the script; instead, an exception will be generated that can be processed in a try catch block , which clearly improves error handling in your application. This is important for some types of applications, servers and daemons, since fatal errors, otherwise, could well lead to the need to restart them. Tests in PHPUnit should also become more convenient to use, since fatal errors could drop the entire test project. Exceptions, unlike errors, can be processed for each test separately.

PHP 7 looks and feels familiar tool, but it is aimed at high performance. The revised Zend Engine and the increase in speed of work lead to big differences from the previous version.

There are quite a few new exception classes in PHP 7 that are designed to handle the types of errors you may encounter. To ensure compatibility between versions, a new Throwable interface has been added ; it can be implemented with both kernel-level exceptions and custom exceptions. This approach is implemented in order to prevent the core exception class from being inherited by the kernel exceptions, which would lead to the appearance of exceptions in previously written code that was not previously present.

Before PHP 7, such code would lead to a fatal script execution error:
 try { thisFunctionDoesNotEvenExist(); //() } catch (\EngineException $e) { //           echo $e->getMessage(); } 


Anonymous classes


Anonymous classes are cousins ​​of anonymous functions that you could use to create the functionality of short and clear objects. Anonymous classes are easily created and used in the same way as regular objects. Here is an example from the documentation.

Before PHP 7:
 class MyLogger { public function log($msg) { print_r($msg . "\n"); } } $pusher->setLogger( new MyLogger() ); 


Using anonymous class:
 $pusher->setLogger(new class { public function log($msg) { print_r($msg . "\n"); } }); 


Anonymous classes are useful when testing with units, in particular when mocking (when simulating the behavior of a real object - approx. Translator) when testing objects and services. Their presence will allow us to avoid using large mocking libraries and frameworks by creating a simple object that supports the interface that we can use for mocking.

CSPRNG functions


Two new functions for generating cryptographically secure strings and integers. The first returns a random string of length $ len:
 random_bytes(int $len); 


The second returns a number in the range $ min ... $ max.
 random_int(int $min, int $max); 


Escape Code Syntax for Unicode


Unlike many other languages, until PHP version 7, there was no way for PHP to specify the escape sequence for the Unicode character in a string. Now, using the escape sequence \ u, you can generate such characters using their UTF-8 code. This is better than the direct insertion of characters, better controlled invisible characters and symbols that have a graphical display different from the value:
 echo "\u{1F602}"; //   


Remember that code that previously worked and used a pair of \ u characters will not work correctly in version 7 due to the changed behavior.

Updated generators


PHP generators also got some nice new features. Now they have a return operator, which can be used to issue some final value that is relevant at the time of the completion of the iteration. It can be used to verify the correctness of the generator. For example, to find out if it has run without errors, which will allow the code that caused the generator to correctly handle any situation that has occurred.

Moreover, generators can return and issue expressions from other generators. Thus, it is possible to break complex operations into simpler ones.

 function genA() { yield 2; yield 3; yield 4; } function genB() { yield 1; yield from genA(); // 'genA'       yield 5; return 'success'; //  ,      } foreach (genB() as $val) { echo "\n $val"; //    1  5 } $genB()->getReturn(); //  'success'    

Expectations


Expectations — improve the assert () function while maintaining backward compatibility. They allow the use of zero-cost assertions in the working code and support the possibility of generating a custom exception when an error occurs during the processing of an assertion, which can be useful during development.

The assert () function has become a language construct in PHP 7. Assertions should only be used during development and testing for debugging purposes. To adjust its behavior, we must use two directives.



Getting ready for the transition from PHP 5 to PHP 7


The advent of PHP version number 7 provided the ability to change / update and even remove functionality that was considered obsolete or, for a while, no longer needed. Such changes may lead to backward compatibility issues with older applications.

Another problem that arises when such versions appear is that the libraries and frameworks that are important to you may not have updates compatible with the new release. The PHP development team tried to make changes as much as possible while maintaining backward compatibility so that migration to the new version was as less time consuming as possible. Relatively new and timely updated applications will most likely be easier to translate into version 7, whereas for older applications you need a weighted decision - are the efforts spent on the received opportunities or better and not updated at all.

Most of the problems are small and can be easily fixed, while others may require much more time and effort. In general, if you saw warnings about the use of obsolete functions before installing PHP 7, then you will most likely see error messages that will stop running your application until they are fixed.

You were warned, right?

Older SAPI and Extensions


Much more important is the fact that old and unnecessary SAPIs were removed, such as the mysql extension (but you don’t use it anymore, right?). For a complete list of extensions and features that have been removed, you can look here and here .
Other extensions and SAPI have been ported to PHP 7.

A lot of old SAPI and extensions have been removed from PHP 7. We believe that they will not be bored.

Same syntax for describing variables


This update introduced some changes in consistency for variable-variable structures. It will allow the use of more progressive expressions with variables, which, in some cases, will lead to a change in the behavior of the code, as shown below:
  //   //   $$foo['bar']['baz'] ${$foo['bar']['baz']} ($$foo)['bar']['baz'] $foo->$bar['baz'] $foo->{$bar['baz']} ($foo->$bar)['baz'] $foo->$bar['baz']() $foo->{$bar['baz']}() ($foo->$bar)['baz']() Foo::$bar['baz']() Foo::{$bar['baz']}() (Foo::$bar)['baz']() 


This will change the behavior of applications accessing variables in this way. On the other hand, you can craft these tricks like this:
 //  () foo()(); // Calls the return of foo() $foo->bar()(); //IIFE (Immediately-invoked function expression     )    JavaScript (function() { //   })(); //  :: $foo::$bar::$baz 


Removed old style tags


Removed or more incorrect opening / closing tags
  <% ...%>, <% = ...%>, <script language = "php"> ... </ script> 

Replacing them with the correct ones is easy, but their use nowadays looks a bit strange, doesn't it?

Incorrect names for classes, interfaces, traits


As a result of additions, such as return types and parameters types, classes, interfaces and traits can no longer be named with the following names:



Such naming can lead to incorrect work of existing applications and libraries, but is easily corrected. The following names are also undesirable to use in the above named quality, since they are reserved for the future:



Refrain from using these words as names, and you will save yourself time afterwards.

A complete list of changes leading to incompatibility can be found here .
You can also use php7cc , this tool will check your code and display potential problems that may arise during the transition to PHP 7.

But there is no better way than installing PHP 7 and seeing it for yourself.

Potential PHP 7 Compatibility Issues



PHP 7 Infrastructure Compatibility


Many hosting services have added PHP 7 support. This is good news for shared hosting providers, since increased productivity will allow them to increase the number of client websites without upgrading hardware, reducing operating costs and increasing revenues. As for clients, they should not expect a dramatic increase in performance under these conditions, and, frankly, shared hosting is not an option in the case of a performance-oriented application.

On the other hand, services that offer private virtual servers or dedicated servers will receive all the benefits of productivity growth. Some PaaS services , such as Heroku, have long supported PHP 7, while others, such as AWS Beanstalk and Oracle OpenShift, lag behind. Check on your PaaS provider’s website whether it has PHP 7 support or whether it is planned for the near future.

IaaS providers allow you to control hardware and install PHP 7 (or compile if you like it more). PHP 7 packages are already available for most IaaS environments.

Software Compatibility with PHP 7


In addition to infrastructure compatibility, you should also be aware of potential software compatibility issues. Known CMS like WordPress, Joomla and Drupal have already added support for PHP 7. Major frameworks such as Symfony and Laravel have done this too.

However, the time has come caution. This support does not apply to third-party code in the form of add-ons, plug-ins, packages, etc., to which your CMS or framework refers. There may be problems, and your task is to make sure that everything is ready for PHP 7.

For active, supported repositories, this should not be a problem. But abandoned repositories without PHP 7 support can make your entire application unusable.

Future of php


In PHP 7, the outdated code was removed, and the green light was given to new features and future performance improvements. Plus, PHP should soon get a performance optimization. Despite the partial loss of backward compatibility with previous versions, most problems that arise are easily solved.

Libraries and frameworks migrate to PHP 7, which leads to the emergence of their new versions. I urge you to try the seven and evaluate the results. Maybe your application is already compatible with the new version and is ready to work on PHP 7, benefiting from its use.

Source: https://habr.com/ru/post/280071/


All Articles