One of the most significant events that happened in the PHP world in 2015 was the release of PHP 7. A full 10 years separate it from the release of the first PHP release number 5. With the increase in the first digit in the version number, PHP 7 introduced a lot of innovations, increased and speed of work. However, the seventh version removed deprecated functionality, which led to some backward compatibility issues, making it difficult to migrate older applications to the new version. This article can serve as a quick guide if you are planning to write new or migrate your existing applications to PHP 7.
Wait, where is PHP 6?
If you haven't worked with PHP for a while, you might be wondering where PHP 6 went, why did we jump from PHP 5 straight to PHP 7? Well, I'll be brief, PHP version 6 was not released. The main feature of version 6 was support for Unicode characters, since PHP is mainly used in web development, and 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 capabilities of the language - from the use of silly emojis as variable and function names, to the powerful functionality of international strings. For example, when another language uses uppercase and lowercase letters differently than English, or when converting a Chinese name to an English name.
PHP6 was ambitious, but it sucked. Therefore, we started working on PHP7, skipping the sixth version in the process.
Unfortunately, this ambitious plan had many more problems than expected.
Much of the codebase had to be ported to support Unicode, both in the core and in the case of important extensions, which turned out to be a tedious and difficult task. This slowed down the development of other language features, which frustrated many PHP developers. Other barriers also appeared, which led to a decline in interest in the development of built-in support for Unicode, and over time the project was completely abandoned. And since a lot of resources, such as books and articles, were written using the PHP 6 name and Unicode support, it was decided to name the new version PHP 7 - just to avoid misunderstandings.
Be that as it may, stop delving into the dark past. Let's take a look at what's new in PHP 7.
PHPStorm
PHPStorm is an editor that is a popular IDE, one of the most functional and convenient, enjoying great popularity among programmers, from beginners to professionals. The editor automatically loads and saves the project structure. An environment was developed in Java and the IntelliJ IDEA platform. Open source code allows you to make any settings and modifications necessary for the developer. There are also several design themes with different interface colors and lighting.
Working with PHPStorm : supports working with both individual files and directories that contain the project. Writing and editing code is carried out with the ability to use autosubstitution and autoreplacement, quick search and transition between functions, class descriptions, including those located in different source files. There is also a built-in help system and contextual hints, which can be called up by pressing the Ctrl + Q combination on the keyboard.
Debugging: carried out in conjunction with the XDebug extension, which must be synchronized with the corresponding PHP option on the server. After which all the necessary functionality, visual tools for debugging, error messages, breakpoints, etc. will become available. It is also possible to configure work in conjunction with Zend Debugger.
SQL databases and databases: working with databases is configured through the Database menu, called through Tool Windows in the main View menu. You can work with all versions of MySQL, Oracle, Microsoft SQL Server and other popular databases, viewing the structure of tables, key fields, relationships, creating various SQL queries and getting the results of their work.
FTP : Allows you to perform all basic operations on a remote server through a regular or secure connection. Editing and automatic file uploading are available, configured through the corresponding menu item.
Framework support: PHPStorm supports the vast majority of standard engines, and also works with major content management systems such as WordPress, Joomla, Drupal.
Performance Wars, PHP 7 vs. PHP 5
Almost all updates brought small performance improvements. However, this time the performance of PHP, compared to earlier versions, has increased much more significantly, becoming one of the most attractive features of PHP 7. This was part of the “PHPNG” project (“php new generation” or “php of the new generation” - approx. . translator
), which affected Zend Engine itself.
Refactoring internal data structures and adding an additional step before compiling the code into an Abstract Syntax Tree (AST) resulted in superior performance and more efficient memory allocation. The numbers themselves look promising - tests performed on real applications show that PHP 7 is on average twice as fast as PHP 5.6, and also uses 50% less memory during query processing, making PHP 7 a strong contender for Facebook's HHVM JIT compiler. Take a look at this infographic from Zend that displays performance for some common CMS and frameworks.
PHP 7 looks familiar, but it's designed for performance. The improved Zend Engine and the resulting performance gains have made a huge difference between it and the previous version.
Reducing memory consumption allows weaker computers to process requests better, making it possible to build microservices around PHP. Internal changes, particularly the AST implementation, also open up opportunities for future optimizations that could further improve performance. A new native implementation of the JIT compiler has been developed with the intention of development in future versions.
Syntactic Sugar in PHP 7
PHP 7 has several new syntax features. Why not extend some of the features of the language itself if they offer a better or easier way to write nice-looking code?
Import declaration grouping
We can now group import declarations for classes that are in the same namespace on one line.
This will help us align the declarations in some meaningful way, or it will simply 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};
Or, if you prefer a multi-line style:
use Framework\Module{ Foo, Bar, Baz };
NULL-coalescent operator
Solves a common problem in PHP.
It occurs when we want to assign a value to a variable that is assigned to another variable, but if the last variable was not assigned a value, then assign some explicit value. Often appears when working with user input. Before PHP 7:
if (isset($foo)) { $bar = $foo; } else { $bar = 'default'; // set $bar to 'default' if $foo is NULL }
In PHP 7:
$bar = $foo ?? 'default';
Can be used with a chain of variables:
$bar = $foo ?? $baz ?? 'default';
“Spaceship” operator
The “spaceship” operator <=> allows for a three-level comparison of two values, allowing you to understand not only whether they are equal or not, but also which of them is greater in the case of 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 and $foo are equal'; case -1: echo '$foo is greater'; case 1: echo '$bar is larger'; }
The values being compared can be of type integer, float, string, or even arrays. How do different values compare to each other? See the documentation.
Download PHP for Windows
Go to the official website and download the current version of PHP. At the time of writing, this is - 7.1.4
. There are several distribution options available on the page. I have Windows 7 x64, so I choose a zip archive with VC14 x64 Thread Safe.
Please note that there are two distribution options available for download: Thread-Safe (TS)
and
Non-Thread-Safe (NTS)
. The choice depends on how you plan to use the interpreter. TS is recommended to be used for a single web services process (for example, configured via the mod_php module for Apache). NTS is recommended for using IIS (Internet Information Service) and alternative FastCGI web servers (for example, Apache with the FastCGI module) and command line.
New in PHP 7
Of course, PHP 7 introduces some exciting new functionality.
Types of scalar parameters and hints on return types
PHP 7 extended the previously existing declaration of parameters in methods (classes, interfaces, and arrays) by adding four scalar types—int, float, bool, and string—as possible parameter types.
In addition, we can optionally specify the type of result returned by the function or method. Supported types are bool, int, float, string, array, callable, class or interface name, and parent (for class methods).
class Calculator { // declare that the parameters are of integer type public function addTwoInts(int $x, int $y): int { // explicitly declare that the method returns an integer return $x + $y; } } Declaring types will allow you to build transparent applications, avoiding passing and returning incorrect values when working with functions. Other positives are the emergence of static code analyzers and IDEs that offer clearer display of code in the absence of DocBlocks documenting notes.
Since PHP is a weakly typed language, some parameter values and return types will be inferred based on context. If we pass the value “3” to a function that has a declared parameter of type int, the interpreter will treat it as an integer and will not generate an error. If you are not happy with this behavior, you can work in strict mode
- by adding the appropriate directive.
declare(strict_types=1); This is set on a per-file basis because a global option would split code repositories into those where the 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 repositories with different settings.
Engine exceptions
With the introduction of kernel-level exceptions, fatal errors that would previously cause script execution to stop can now be easily caught and handled.
Errors such as calling a non-existent method will no longer stop the script, but will instead throw an exception that can be handled in a try catch
, which clearly improves error handling in your application. This is important for some types of applications, servers, and daemons, since fatal errors might otherwise require a restart. Tests in PHPUnit should also become more user-friendly, since fatal errors could crash the entire test project. Exceptions, unlike errors, can be handled on a per-test basis.
PHP 7 looks and feels familiar, but it's focused on performance. The redesigned Zend Engine and increased speed lead to big differences from the previous version.
PHP 7 introduces quite a few new exception classes to handle the types of errors you may encounter. To ensure compatibility between versions, a new Throwable
; it can be implemented by both kernel-level exceptions and user-defined exceptions. This approach is implemented to prevent the base class of exceptions from being inherited by kernel exceptions, which would lead to the appearance of exceptions in previously written code that did not exist before.
Before PHP 7, this code would have resulted in a fatal script error:
try { thisFunctionDoesNotEvenExist(); //ThisFunction Doesn't Even Exist() } catch (\EngineException $e) { // Clean up after ourselves and write error information to the log echo $e->getMessage(); }
Anonymous classes
Anonymous classes are the cousins of anonymous functions, which you could use to create short and clear object functionality.
Anonymous classes are easy to create and use 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 an anonymous class:
$pusher->setLogger(new class { public function log($msg) { print_r($msg . "\n"); } });
Anonymous classes are useful when testing units, in particular when mocking (simulating the behavior of a real object - translator's note) when testing objects and services. Having them will allow us to avoid the use of large mocking libraries and frameworks by creating a simple object that supports an 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, prior to PHP version 7, PHP did not have a way to specify an on-line escape sequence for a Unicode character.
Now, using the \u escape sequence, you can generate such characters using their code from the UTF-8 set. This is better than inserting characters directly, and has better control over invisible characters and characters that have a graphical representation different from the meaning: echo "\u{1F602}"; // displays a smiley face Remember that code that previously worked using the \u character pair will not work correctly in version 7 due to changed behavior.
Updated generators
Generators in PHP also get some nice new features.
Now they have a return statement that can be used to return some final value that is relevant at the time the iteration is completed. It can be used to check that the generator is running correctly. For example, find out whether it executed without errors, which will allow the code that called the generator to correctly handle any situation that arises. Moreover, generators can return and output expressions from other generators. In this way, complex operations can be broken down into simpler ones.
function genA() { yield 2; yield 3; yield 4; } function genB() { yield 1; yield from genA(); // 'genA' is called and processed in this place yield 5; return 'success'; // final result that we can check later } foreach (genB() as $val) { echo "\n $val"; // will return values from 1 to 5 } $genB()->getReturn(); // return 'success' if there are no errors
Expectations
Expectations—improvement of the assert() function while maintaining backward compatibility.
They allow you to use zero-cost assertions in production code and support the ability to throw a custom exception when an error occurs while executing an assertion, which can be useful during development. assert() function
became a language construct in PHP 7. Assertions should only be used during development and testing for debugging purposes. To configure its behavior we must use two directives.
- zend.assertions 1: generate and execute code (development mode) (default) 0: generate code, but bypass it at runtime -1: do not generate code, making it zero-cost code (production code mode)
- assert.exception 1: throws when an assertion fails by creating a corresponding exception object, or by throwing an AssertionError object if no such object was created 0: uses or throws a Throwable as described above, but only throws a warning based on that object rather than throwing an exception using it (PHP 5 compatible behavior)
CodeLobster
CodeLobster is one of the most famous editors, which is written in the C++ programming language, has a flexible interface and many settings that allow you to work with any WEB technologies.
Working with CodeLobster: by default, all the necessary functionality is built in, allowing you to work with individual files and projects in directories. The program remembers the project structure and provides simple and fast navigation, identification and highlighting of incorrect areas with errors. It also allows you to work with files containing pieces of code written in different languages, for example, PHP, JavaScript, HTML, which are automatically detected and highlighted in different colors for convenience. For all main functions there are duplicate key combinations that are quickly remembered, make work easier and faster. Built-in help, with tooltips, quick function substitution, etc.
Enabling dynamic help through the Dynamic Help tab will allow you to automatically select and display a list of links to files that contain the required code elements.
Debugging capability: installing the XDebug extension, as well as enabling the corresponding option on the server, allowing you to debug, edit and eliminate errors, with instant verification of the result of running a script or subroutine.
Databases and SQL : there is a built-in client for working with all major types of databases, as well as the ability to simultaneously create multiple connections, generate queries, save them and load them from files with the sql extension.
FTP : the built-in FTP client has advanced functionality, coping well with remote work with files on the server, including for those projects that use a large amount of data. Connection via any of the existing types of protocols, including encrypted connections.
Framework support: The basic version of CodeLobster already has everything you need to work with most popular PHP libraries, as well as content management systems. Loading and connecting frameworks is carried out directly from the editor environment.
This is what the beginning of creating an online store using Magento looks like:
It is also possible to work with such popular CMS as Joomla, Drupal, WordPress. The editor will automatically download and install the latest versions of any of the specified systems, further updating it if necessary.
Preparing for the transition from PHP 5 to PHP 7
The introduction of PHP version 7 provided the opportunity to change/update and even remove functionality that was considered obsolete or, for some time, no longer needed.
Such changes may cause backward compatibility issues for older applications. Another problem with these releases 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 to ensure that migrating to a new version was as painless as possible. Relatively new and timely updated applications will most likely be easier to migrate to version 7, while older applications require an informed decision - whether the effort is worth the new features or whether it is better not to update at all.
Most problems are minor and can be easily fixed, while others may require much more time and effort. In general, if you saw warnings about using deprecated features before installing PHP 7, then you will most likely see error messages that will stop your application from running until they are resolved.
You were warned, right?
Old SAPIs 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?). You can see the full list of extensions and features that have been removed here and here. Other extensions and SAPIs have been ported to PHP 7.
A lot of old SAPIs and extensions have been removed from PHP 7. We believe that they will not be missed.
Monotonous syntax for describing variables
This update introduced some consistency changes for variable-variable constructs.
It will allow the use of more progressive expressions with variables, which, in some cases, will lead to changes in the behavior of the code, as shown below: // old meaning // new meaning $$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 a specified way. On the other hand, you can do tricks like this:
// nested () foo() (); // Calls the return of foo() $foo->bar())(); //IIFE (Immediately-invoked function expression) syntax as in JavaScript (function() { // function body })(); // Nested :: $foo::$bar::$baz
Old style tags removed
Opening/closing tags have been removed or are no longer correct, , ... It’s easy to replace them with correct ones, but their use looks a little strange nowadays, doesn’t it?
Incorrect names for classes, interfaces, traits
As a result of additions such as return types and parameters, classes, interfaces, and traits can no longer be called by these names:
- bool
- int
- float
- string
- NULL
- true
- false
Such naming can lead to incorrect operation of existing applications and libraries, but can be easily corrected. The following names are also not recommended to be used in the above-mentioned capacity, since they are reserved for the future:
- resource
- object
- mixed
- numeric
Refrain from using these words as names and you will save yourself time later.
The full 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 when migrating to PHP 7.
But there is no better way than installing PHP 7 and seeing everything with your own eyes.
Potential PHP 7 compatibility issues
PHP 7 framework compatibility
Many hosting services have added support for PHP 7. This is good news for shared hosting providers, as the increased performance will allow them to increase the number of client websites without upgrading hardware, reducing operating costs and increasing revenue.
As for clients, they shouldn't expect dramatic performance gains under these conditions, and frankly, shared hosting isn't an option for a performance-oriented application anyway. On the other hand, services that offer private virtual servers or dedicated servers will enjoy all the benefits of increased productivity. Some PaaS services, such as Heroku, have long supported PHP 7, while others, such as AWS Beanstalk and Oracle OpenShift, are lagging behind. Check with your PaaS provider's website to see if they have PHP 7 support or are planning to support it in the near future.
IaaS providers allow you to control the hardware and install PHP 7 (or compile it if you prefer). PHP 7 packages are already available for most IaaS environments.
Software compatibility with PHP 7
In addition to infrastructure compatibility, you also need to be aware of potential software compatibility issues.
Well-known CMSs like WordPress, Joomla and Drupal have already added support for PHP 7. Major frameworks such as Symfony and Laravel have also done so. However, the time has come for caution. This support does not extend to third party code in the form of add-ons, plugins, packages, etc. that your CMS or framework accesses. There may be problems, and your task is to make sure that everything is ready to work under PHP 7.
For active, maintained repositories, this should not be a problem. But abandoned repositories without PHP 7 support can render your entire application unusable.
The future of PHP
PHP 7 removed legacy code and gave the green light to new features and future efficiency improvements.
Plus, PHP should be getting performance optimizations soon. Despite the partial loss of backward compatibility with previous versions, most problems that arise can be easily resolved. Libraries and frameworks migrate to PHP 7, which leads to the appearance of their new versions. I encourage you to try the seven and evaluate the results. Perhaps your application is already compatible with the new version and is ready to run on PHP 7, benefiting from its use.
Where to write the code?
IDE
Try each development environment and understand which platform you are most comfortable working with:
- PHPStorm;
- Netbeans;
- Aptana Studio;
- Eclipse.
Code editors for PHP projects
- Sublime Text;
- Visual Studio Code;
- Atom;
- Coda;
- jEdit;
- Programmer's Notepad;
- Komodo Edit.
A selection of free cross-platform environments for web development
tproger.ru