PHP 7 functions. Old style tags removed

PHP is a programming language that is mainly used in web development, usually in the back-end part. PHP has a fairly long history - its first version appeared more than 20 years ago, in 1995. During this time, 7 versions of PHP were released, the last of which appeared in December 2015. This will be discussed in this article.

The release of PHP 7.0 was a breakthrough in its own way, since it was based on phpng - an experimental and actively developing PHP project, the name of which stands for “PHP Next Generation” - “The Next Generation of PHP”. This technology could be used in previous versions of PHP, but it was in PHP 7 that it was introduced as fundamental. During its development, the goal was to increase PHP performance without losing compatibility.

Zend Engine

PHP 7 is based on the third version of Zend Engine, in which the phpng project was developed.

Innovations

First of all, the innovations in PHP 7 affected the most important parameters for application development - performance and memory consumption.

The main change that is primarily mentioned when talking about PHP 7 is performance improvement: PHP 7 performance is close to that of HHVM (a system developed by Facebook that allows you to speed up the conversion of PHP code several times). Not the least reason for this is that the co-founder of Zend Technologies (the PHP core developer company) Zeev Souraski considers HHVM as one of Zend's competitors. And the leading developer of PHP 7 at Zend Technologies and the author of phpng, Dmitry Stogov, assures that the difference in performance between PHP 5.0 and PHP 7 on the synthetic bench.php test is 14 times. In practice, most users tend to believe that PHP 7 is approximately twice as fast as the previous version.

HHVM uses the so-called JIT (Just-In-Time) compilation to convert code - despite the fact that JIT did not appear in version 7 of PHP, PHP 7 supports better migration, which allows you to improve performance significantly. It is this new level of performance that Dmitry Stogov highlights as the main feature of PHP 7.

Performance improvements were also achieved due to the fact that the compiler now generates more efficient and shorter bytecode.

Nowadays, it is extremely important to think about users of not only desktop but also mobile devices, so PHP 7 developers have improved engine performance and reduced memory consumption, and also added the ability to use native local storage. In addition, PHP 7 allows you to perform asynchronous tasks.

By the way, during the development, popular trends in reducing the consumption of planetary resources were also taken into account, so PHP 7 has ability to handle more traffic, using the same server resources.

New features

PHP 7 has many new features, all of which make development more convenient and simpler. Below you can familiarize yourself with some of them.

  • Two new exception classes(Exception and Error) - if in previous versions of PHP it was impossible to handle fatal errors, then in the new release the actions leading to this throw exceptions, that is, the script will not terminate.
  • Anonymous classes- PHP 7 now supports this type of class, which is often used in C++ and Java to perform callback functions. These classes are mainly used to create simple elements:

setLogger(new Logger()); // PHP 7+ code $util->setLogger(new class ( public function log($msg) ( echo $msg; ) ));

Anonymous classes can be nested, but they will not have access to the protected or private properties of the outer class.

  • Possibility to specify scalar types(Scalar Type Hints) - in previous versions of PHP it was possible to specify the type of accepted values; you can now also specify scalar types:

Strings (`string`), integers (`int`), numbers (`float`), bubbles (`bool`).

This innovation is aimed at making code easier to write and more readable. But the use of these values ​​as class names is strictly prohibited, because this may lead to critical errors.

  • Shorthand use construct - PHP 7 now has the ability to combine declarations of use groups, which will undoubtedly have a positive effect on both the speed of work and the perception of the code:
  • New operators Null coalescing operator(??) And Combined Comparison Operator (<=>, also known as Spaceship Operator) - these two new operators, which some refer to as syntactic sugar, will help you write more concise and understandable code.

Null coalescing operator is a coalescing operator that checks whether a variable exists and returns its value (or its default value):

$action = $_POST["action"] ?? "index";

Combined Comparison Operator is a comparison operator that is useful for use in callback functions for usort(). It compares two values ​​and, depending on the result, returns -1, 0 or 1:

Function order_func($a, $b) ( return $a<=>$b; )

The priority of this operation is equal to the priorities of other comparison operations, but it cannot be associated with the previous call, because it is a non-associative operator.

  • Function assert()- in PHP 7 this function is processed in a special way so that overhead is eliminated; you can use it for debugging and disable it later.
  • Filtration unserialize()- This innovation will ensure the security of object serialization. The developer himself will be able to determine which classes should be processed and which should not.
  • Performance integers as 64-bit in PHP 7 for Windows x64: PHP now supports strings longer than 231 bytes in 64-bit builds.
  • Delegation of generators- with help a complex generator can be divided into several smaller ones. Like some other innovations, this innovation is aimed at writing cleaner and more reusable code.
  • The emergence of a new class IntlChar- it increases the set of capabilities of the library for localizing International Components for Unicode applications and has class methods and constants for working with Unicode.
  • Ability to define arrays as constant values ​​that are declared via define().
  • Ability to assign reserved keywords to method names.
  • The appearance of a new simple value identifier PHP_INT_MIN.

As for old features, some of the most unused features were excluded: for example, ASP and script tags were removed, as well as POSIX-compliant regular expressions and the ext/mysql extension.

PHP and web servers

PHP is widely used in writing many web applications because... this language is compatible with various web servers (Apache, Nginx, IIS), databases (MySQL, Postgre, MongoDB, etc.), as well as operating systems.
Therefore, innovations have traditionally affected not only the language as a whole, but also those aspects of it that are related to hosting.

First of all, PHP 7 introduced Abstract syntax tree(AST) is an abstract syntax tree that is an intermediate link in the compilation process. It is on this model that the parser is now based. Thanks to this, you can now create more performant operating code.

Another innovation is Uniform Variable Syntax- universal syntax for variables. This allows, on the one hand, to resolve some of the inconsistencies that are associated with calculating the values ​​of variables, but, on the other hand, it creates the need to rewrite some rarely used parts of the code.

Let's return once again to the increase in performance of PHP 7: this will have a positive effect on the functionality of all hosting providers, because they will be able to increase the number of their users without increasing the number of servers or other improvements.

One of the reasons for the increased productivity is optimization of internal data structure, which significantly improved the process of working with memory.

We can't help but mention some backward compatibility issues that may arise when migrating to PHP 7. For example, you can no longer use multiple default statements in a switch, because otherwise you will see an error. However, overall these problems are minor compared to the new features that PHP 7 offers.

Conclusion

The release of PHP 7 is not just the release of a new version of PHP, but a definite starting point for the next generation of PHP versions. The many innovations in PHP 7 result in cleaner, more convenient and understandable code, significantly increased productivity and much more, which you can evaluate for yourself by upgrading your virtual server to the seventh version of PHP.

According to some studies, about 80% of all websites are written on it. And this is not at all strange, because even such network giants as In contact with And Facebook, were created using it. The popularity can also be judged by the fact that the query “” is requested in search engines much more often than other languages. So for one request perl hosting falls 150 – the above hosting php.

The language was created in 1994 and was originally a set of scripts. Over time, the scripts were converted into a C interpreter.

Main features and capabilities of the PHP language:

  • ability to work with various web servers ( ,IIS);
  • ease of learning and flexibility in work;
  • support for working with databases – , MSSQL, Oracle, Postgre, MongoDB and others;
  • For popular operating systems there are corresponding PHP packages, i.e. you can create websites on;
  • Compatible with most hosting services that are provided by providers. You can easily host a website written in PHP on any hosting. How to secure PHP on the server? Our advice.
  • The PHP language does not stand still and is constantly evolving, which attracts developers from all over the world.

What versions of PHP are current at the moment?

By right, PHP versions 4 and 5 are considered current. Version 4 has its own popularity and is used for writing various web applications. PHP 5 has many additional features, but in turn, is not fully compatible with the fourth version of the language. That's why Some programs (written in PHP 4) will not work in the PHP 5 environment. Modules are often used as additional tools to the core of the language. For example, special modules have been developed for working with graphics, or modules that implement interactions with various databases.

After the release of the 5th version of the language, everyone was expecting the sixth. But PHP 6 was never able to realize itself due to problems with Unicode support, so in 2010 the development and implementation of this version was stopped.

PHP 7 is a new version with new features.

Not so long ago, December 3, 2015, a new release of the popular programming language has been released -PHP 7.0.0 , which gave rise to the development of the PHP 7 series. The language has already won its fans over its twenty-year history of existence. A general-purpose scripting language is used to create various web applications, including writing paid and free CMS. For example, Joomla!, Drupal, WordPress, etc.

Further Let's talk about the new features of PHP 7 and let's figure out why the developers were waiting for it so much. Indeed, despite frequent criticism of this language, most hosting providers support it, including installing the latest versions of PHP. The language is the most popular in terms of online use. The new version is essentially experimental and is based on phpng (the next generation of PHP), based on the principle of increasing performance by reducing memory consumption.

PHP 7 language is developed with the addition of a new version of Zend Engine. If we compare it with the previous version 5.6 (the new release of which appeared in November of the same year), then web developers of the language primarily note the improved performance of the new technology: PHP 7 is twice as fast as its predecessor.

Let's look at the points,what does the new version of PHP offer? :

  • full-fledged 64-bit support systems;
  • Memory usage is much reduced;
  • added abstract syntax tree functionality;
  • most fatal errors turn into exceptions;
  • improved exception hierarchy;
  • random generator numbers have become more secure;
  • anonymous classes;
  • removed obsolete SAPIs and extensions (sapi/aolserver, sapi/apache sapi/apache_hooks, sapi/apache2filter, sapi/caudium, sapi/continuity, sapi/isapi, sapi/milter, sapi/nsapi, sapi/phttpd, sapi/pi3web, sapi/roxen, sapi/thttpd, sapi/tux, sapi/webjames, ext/mssql and ext/sybase_ct);
  • stopping support for PHP 4 style constructors where the constructor name is the same as the class name;
  • created Closure::call() method;
  • in addition there is openssl ALPN TLS extension support(Application-Layer Protocol Negotiation) to negotiate application-layer protocols that are used to provide a secure connection. Applicable in SPDY and HTTP/2;
  • NULL concatenation operator ?? ;
  • providing grouping of definitions in the use statement (for example, use DoctrineCommonCollectionsExpr( Comparison, Value, CompositeExpression );) and much more.

You can download and learn more about all the benefits of the new version of PHP at official page, you can also download the migration guide there. The new release is not just another version of the PHP language, but the beginning of the development of a new path in programming languages. It took two years of diligent development to launch it, which helped create an improved product.

If you are looking for a reliable 7th version , contact our company Hyper Host Our shared hosting servers support PHP 7. We hope you will like the new features. We, in turn, will be happy to help!

7435 times 1 Viewed times today

Finally, PHP 7.1 has been released, a new minor version of PHP that includes a number of new features, changes and bug fixes. In this article, we'll look at some of the great new features in PHP 7.1, namely:

  • Iterable pseudotype
  • Closures via callback functions
  • Square bracket syntax for list()
  • Support for keys in a list
  • Visibility of class constants
  • Nullable types
  • Functions of type void
  • Catching exceptions of different types
  • "Too few arguments" exception

For your convenience, I will also refer to the relevant RFCs throughout the article.

Before we begin: Would you like to try PHP 7.1 without making a mess of your current programming environment? Then Docker is your best friend! PHP 7.1 can be easily set up with Docker using one of these images.

To run a 7.1 container:

Docker run -v /Users/apple/Workplace/php/:/php -it php:7.1-rc bash

This will download (if you don't already have similar files on your local device) Docker images for php:7.1-rc , then launch the container and navigate to it using the tooltips. Move the option maps -v /Users/apple/Workplace/php/:/php from the /Users/apple/Workplace/php directory on the host computer to the /php directory inside the Docker container. This way, all files inside /Users/apple/Workplace/php will be available in the /php container directory.
Now go to the /php directory.

Super! Now we are ready to try out the new features of PHP 7.1.

1. Iterable pseudotype

Let's say we have a getUserNames function that takes a list of users and returns their names as a list.

Function getUserNames($users) ( return nikic\map(function($user)( return $user->name; ) , $users); )

The $users parameter can be an array or an object implementing the Traversable function. Before PHP 7, it was not possible to give this function any type hints because there was no generic type that could match both an array and a Traversable object.

To solve this problem, PHP 7.1 introduced a new iterable pseudotype, which we can use to set type values ​​for anything that can be iterated using foreach .

Function getUserNames(iterable $users): iterable ( return nikic\map(function($user)( return $user->name; ) , $users); )

This function can now accept arrays, iterables, and generators.

2. Closures via callback functions

This functionality allows us to create closure mechanisms through any called function. Let's look at one example to understand this better.

Class MyClass ( public function getCallback() ( return Closure::fromCallable([$this, "callback"]); ) public function callback($value) ( ​​echo $value . PHP_EOL; ) ) $callback = (new MyClass)- >getCallback(); $callback("Hello World");

This is probably not the best example to explain why we need this function, but it can be used to illustrate exactly how it works. Using the Closure::fromCallable function has several advantages over more traditional methods.

Improved error correction mechanism - When working with Closure::fromCallable, errors are shown in the correct place, not where we use the called function. This greatly simplifies the process of fixing bugs.

Transferring Volumes – The example above will work fine even if the callback is a private/protected MyClass method.

Performance – A function like this also improves performance by avoiding redundant checks to ensure that a given called function is actually a callable function.

3. Square Bracket Syntax for List()

Short Array Syntax was one of the awesome features added in PHP 5.4 that made working with arrays much easier and more convenient. The shortlist syntax now allows us to use square brackets instead of list() to assign variables to an array.

//prior to php 7.1 list($firstName, $lastName) = ["John", "Doe"]; // php 7.1 [$firstName, $lastName] = ["John", "Doe"];

4. Support keys in the list

Before PHP7, the list() function only supported number-indexed arrays whose index starts at zero. We couldn't use this function with associative arrays.

Now the new functionality allows us to specify keys when destructuring arrays.

$user = ["first_name" => "John", "last_name" => "Doe"]; ["first_name" => $firstName, "last_name" => $lastName]= $user;

As an interesting side effect, we can now assign only the necessary keys from the array.

["last_name" => $lastName] = $user;

You can also destructure multidimensional arrays using lists within a list.

$users = [ ["name" => "John Doe", "age" => 29], ["name" => "Sam", "age" => 36] ]; [["name" => $name1, "age" => $age1],["name" => $name2, "age" => $age2]] = $users;

5. Visibility of class constants

Class constants help us give a meaningful name to the value that is used in a given class. These constants were always public and could be accessed from the outer class. But we don’t always want to expose them to the outside world, do we?
In PHP7.1, we can assign visibility modifiers to class constants in the same way we do with methods and properties.

Class PostValidator ( protected const MAX_LENGTH = 100; public function validateTitle($title) ( if(strlen($title) > self::MAX_LENGTH) ( throw new \Exception("Title is too long"); ) return true; ) )

Here the MAX_LENGHT constant is an internal constant of the PostValidator class and we don't want this value to be exposed to the outside world.

6. Nullable types

This functionality allows us to provide hints about the type of a function, while allowing null values ​​to be used as a parameter or return. We can set a parameter or result to be of type Null by placing a question mark (?) in front of the type hint.

Function sayHello(?string $name) ( echo "Hello " . $name . PHP_EOL; ) sayHello(null); // Hello sayHello("John"); //Hello John

This works the same way for returns.

Class Cookie ( protected $jar; public function get(string $key) : ?string ( if(isset($this->jar[$key])) ( return $this->jar[$key]; ) return null; ) )

7. Functions of type void

Since PHP 7, we can specify the type of value that a function should return as output. Sometimes there are times when you need to specify that a function should not return any value at all.

Class Cookie ( protected $jar; public function set(string $key, $value) : void ( $this->jar[$key] = $value; ) )

When return is set to void , the function either must omit a return statement altogether or can have an empty return statement. The function should not return any values.

8. Catching exceptions of different types

When dealing with exceptions, sometimes we may need to handle multiple exceptions in the same way. Typically, we would have to create several separate catching blocks to handle different types of exceptions.

Try ( // somthing ) catch(MissingParameterException $e) ( throw new \InvalidArgumentException($e->getMessage()); ) catch(IllegalOptionException $e) ( throw new \InvalidArgumentException($e->getMessage()); )

In PHP 7.1 we can handle multiple exceptions within a single catch block.

Try ( // something ) catch (MissingParameterException | IllegalOptionException $e) ( throw new \InvalidArgumentException($e->getMessage()); )

Multiple exceptions are separated using a single pipelining symbol. This will avoid duplicating the same code to handle different types of exceptions.

9. “Too few arguments” exception

As of PHP 7, we can call a function with fewer arguments than actually required. In this case, the environment will only issue a warning about missing arguments, but will continue executing the function. Sometimes this can cause the function to behave strangely or unexpectedly.

In PHP 7.1, calling a function without the required parameters will throw an ArgumentCountError exception.

Function sayHello($name) ( echo "Hello " . $name; ) sayHello(); // Fatal error: Uncaught ArgumentCountError: Too few arguments to function sayHello(), 0 passed in...

Throwing an exception will help us immediately resolve such problems by avoiding unexpected behavior of the function. However, this change is incompatible with earlier versions and may break your current applications. Therefore, we recommend that you make sure that everything is fine with your applications before upgrading to a newer version.

Results

In this article, we have discussed some of the important features added in PHP 7.1. To learn more about the new features and changes in PHP 7.1, we recommend that you read the official downgrade guide. Am I missing any important feature? Write in the comments below:)

Is it worth upgrading to the new version of PHP 7.0? – It’s definitely worth it, don’t even think about it - go ahead!

The seventh version has quite a lot of innovations. The main ones:

  • PHP 7 core uses PHPNG. The new core gives sites a performance increase of 40%;
  • type Hints and return values. Now, when declaring a function, you can specify its own type for each variable, as well as the data type that the function will return. Available types: int, float, string and bool;
  • combination comparison operator and much more.

Some extensions have been removed in PHP 7:

  • mysql

Already in PHP 5.6.x the use of these extensions was undesirable. Instead of "mysql" you should use "PDO", and instead of ereg → preg .

You can learn more about the new PHP 7 products on the official page

Is it worth upgrading to PHP 7?

For now, the easiest thing you can do to improve site performance is to upgrade to PHP 7.0.x. Speed ​​gains also depend on how your project is written. If you are still in doubt, let's show some comparisons:

Benchmarks PHP 5.6 vs PHP 7 for some frameworks (Zend framework, Magento, Drupal, Mediawiki, WordPress, Laravel, SugarCRM, etc.):

For all frameworks, the performance gain is significant. Let's see how things stand with kernel functions and constructs:

Benchmarks PHP 5.6 vs PHP 7 for kernel functions and constructs:

If the graphs convince you, you can try migrating your site to a new version of PHP and feel the gains on a real project.

Colleagues from Elasticweb said that before launching a new server with PHP 7, they launched a large government project on it running on Laravel 5. This was a kind of performance test of the new version of PHP and the server as a whole. Previously, this project was on a server with PHP 5.6. After moving the site, pages began to open significantly faster, while resource usage was cut in half.

To prepare for the move to PHP 7, they used the PHP 7 Migration Assistant Report (MAR). Most popular CMS/Frameworks are already compatible with PHP 7, so the main task was to test custom plugins.

WordPress 4, Drupal 8/7 and the latest version of Joomla are ready for PHP 7!

PHP 7.3 is expected to be released in the fall of 2018. However, preparatory work on a new version of the language is already underway. All discussions by the PHP core development team are conducted in open areas, therefore, information about the proposed innovations in PHP 7.3 is available to anyone. So, at the moment, the innovations in PHP 7.3 include:

  • More flexible syntax for writing heredoc and nowdoc strings;
  • Gaining the ability to use a comma as a terminating character in calls to methods and functions;
  • Exceptions when executing json_encode() and json_decode() ;
  • Using reference variables in the list() function;
  • Introduction of the is_countable() function.

Let's go through the list above in more detail.

More flexible syntax for writing heredoc and nowdoc strings

This declaration method is especially convenient when you have to work with strings located on several lines. Currently, this syntax has particularly strict requirements for ending string declarations in this way. Consider the line:

$foo =<<

In it, the last IDENTIFIER must be the first sequence of characters on a new line, and there must not be any other characters after this identifier, with the exception of spaces and tabs.

With the release of PHP 7.3, the requirements for using the heredoc and nowdoc syntax will be somewhat relaxed. Namely:

  • The identifier that ends a line declaration does not have to be the first sequence of characters on a new line;
  • The final declaration of a string identifier may be preceded by either a space or a tab (but not both spaces and tabs);
  • All spaces and tabs preceding the final line declaration will be stripped from the declared line;
  • After the final identifier, other language expressions may be used on the current line.

So the following code will not cause any errors:

$foo = ["foo", "bar",<<

Will display:

Array(5) ( => string(3) "foo" => string(3) "bar" => string(29) "baz - hello world! -- ahoy" => string(3) "qux" => string(4) "quux" )

Gaining the ability to use a comma as a terminating character in method and function calls

This innovation is a logical continuation of the already used ability to leave optional commas when declaring an array or the namespace used:

# Currently possible use Foo\Bar\( Foo, Bar, ); $foo = [ "foo", "bar", ];

The only time such a detail is at all useful is when displaying changes in version control systems (for example, git) it does not display an extra line, as if you had to add a trailing comma. Thus, with PHP 7.3 the following syntax will be available:

Unset($foo, $bar, $baz,);

class Foo ( public function __construct(...$args) ( // ) public function bar(...$args) ( // ) public function __invoke(...$args) ( // ) ) $foo = new Foo("constructor", "bar",); $foo->bar("method", "bar",);

$foo("invoke", "bar",);

However, using the syntax below in declaring functions and methods will still cause an error:

# Parse error function bar($a, $b,) ( // )

Personally, I am skeptical about this innovation and if I use it, it will be extremely rare.

RFC

Exceptions when executing json_encode and json_decode

It is proposed to introduce a new option JSON_THROW_ON_ERROR that can be passed to the json_encode() and json_decode() functions in order to change their behavior. At the moment, including PHP 7.2, if an error occurs while executing the specified functions, false will be returned as the result. This is a great place for bugs, since not every developer parses the response for false in the hope of getting a valid result. With the release of PHP 7.3, the code that processes json can be contained in standard try-catch blocks to catch \JsonException exceptions:

# Parse error function bar($a, $b,) ( // )

Try ( json_decode("(", false, 512, JSON_THROW_ON_ERROR); ) catch (\JsonException $exception) ( echo $exception->getMessage(); // echoes "Syntax error" )

The list() function is used to quickly assign array values ​​to variables. Until now, including PHP 7.2, there is no way to assign array values ​​to variables by reference. In current versions of PHP, the following code will result in a Fatal Error:

$arr = ["apple", "orange"]; list($a, &$b) = $arr; $b = "banana"; echo $arr; // Fatal error: and list() assignments cannot be by reference in .. on line ..

In contrast, using PHP 7.3, this code will work and 'banana' will be printed from the $arr variable.

# Parse error function bar($a, $b,) ( // )

Introduction of the is_countable() function

PHP 7.2 deprecated many features as well as code usage. So, when passing the count() function to a non-countable variable, PHP showed a warning. To avoid this warning, the variable passed to the count() function must either be an array or implement the \Countable interface:

If (is_array($foo) || $foo instanceof Countable) ( // $foo is countable )

In order not to constantly copy-paste these two conditions, it is proposed to introduce the is_countable() function, which combines these conditions. The code above in PHP 7.3 might look like this:

If (is_countable($foo)) ( // $foo is countable )