Translation PHP7 Introduction: New Features and removal features

Source: Internet
Author: User
Tags deprecated rfc throwable try catch what php hosting shared hosting aws beanstalk
Translation PHP7 Introduction: New Features and removal features

/** * Source: Https://www.toptal.com/php/php-7-performance-features * @author dogstar.huang 
 
  
   
   2016-03-13 */
 
  

In the PHP world, one of the most exciting messages of the 2015 was the release of PHP 7, which lasted 10 years from the last major version of PHP 5. After a huge step forward, PHP 7 introduces a number of new features and performance upgrades.

However, with some compatibility interruptions, it removes old, deprecated functionality, making it more difficult for older applications to migrate to the new version. If you're planning to move existing apps over PHP 7 or build new apps, this guide should be a quick wizard for what's expected to happen.

But wait, where's PHP 6 going?

If you haven't been using PHP in your job recently, you might wonder what happened to PHP 6, and why would you jump directly from PHP 5 to PHP 7? Well, long story short, PHP 6 failed. Since PHP is primarily used for Web site development and the site needs Unicode, the main feature of version 6 is local support for Unicode, so it makes sense to take Unicode to PHP.

The idea is to bring complete support for Unicode to its core. This would have allowed the ability to extend capabilities to languages, from using funny emoji as variables and function names, to powerful internationalized character functions. For example, when another language differs from English with uppercase and lowercase characters, or when the name of a Chinese character needs to be converted to English.

PHP 6 is ambitious, but bad. That's why we ended up with PHP 7来 in this process, skipping 6 directly.

Unfortunately, the ambitious plan proved to be a bigger problem than expected. Most code libraries need to be ported to support Unicode in both core and critical extensions, proving cumbersome and complex. This slows down the development of other features in the language and, in the process, makes many PHP developers feel frustrated. The presence of additional barriers has greatly reduced the interest in developing native Unicode support, resulting in the project being abandoned.

Because resources like books and articles have been compiled for PHP 6 and its Unicode support, to avoid confusing the new version will be named PHP 7.

Anyway, the past is a terrible thing, let's see what PHP 7 brings.

Performance battle, PHP 7 vs PHP 5

With almost all updates, a slight performance upgrade is predictable. This time, however, PHP has brought more important improvements than previous versions, making pure performance the most appealing feature of PHP 7. This comes from part of the "Phpng" project, which captures the internal structure of the Zend engine itself.

By refactoring the internal data structure and adding an intermediate step to the code compilation in the abstract Syntax tree (AST) Form, the result is superior performance and more efficient memory allocation. The numbers themselves look very hopeful: benchmarks in real-world applications have shown that PHP 7 is averaging twice times faster than PHP 5.6, and that it reduces memory consumption by 50% during requests, making PHP 70% a powerful opponent for Facebook HHVM JIT compilers. Can look down from Zend for some general purpose CMS and the framework depicts the chart information.

PHP 7 looks and feels familiar, but it adjusts for performance. The refined Zend engine and the resulting performance have made a huge difference.

With the opportunity to build microservices around PHP, the reduction in memory consumption also allows smaller machines to handle requests better. Internal changes, especially the AST implementation, also open the possibility of future optimizations that can push performance further. A new, in-house JIT implementation is being considered for future releases.

PHP 7 Syntax sugar

Along with PHP 7 comes the new syntax feature. They provide a better, or easier, way to make your code more enjoyable to write and look more comfortable without the ability to extend the language itself.

Group Import Declaration

Now we can simplify the class group import declaration grouping from the same namespace into a use line. This should be possible in a meaningful way or simply save some bytes in the file to help align the declarations.

Use Framework\module\foo;use framework\module\bar;use Framework\module\baz;

Using PHP 7 We can use:

Use Framework\module\{foo, Bar, Baz};

Or, if you are more inclined to multi-line style:

Use framework\module{    Foo,    Bar,    Baz};

Null merge operator

This solves a common problem in PHP programming, when we want to assign the value of a variable to another variable, if the latter actually has a setting, it provides a different value for it. Typically used when we process user-supplied input.

Before PHP 7:

if (Isset ($foo)) {    $bar = $foo;} else {    $bar = ' default ';//We would give $bar the value ' default ' if $foo is NUL L

After PHP 7:

$bar = $foo?? ' Default ';

You can also concatenate multiple variables in this way:

$bar = $foo?? $baz?? ' Default ';

Spaceship operator

The spaceship operator <=> allows three ways to compare two values, not only means if they are equal, but also which one is larger, by returning the inequality of 1,0 or-1.

We can make different actions depending on the value:

Switch ($bar <=> $foo) {case    0:        Echo ' $bar and $foo is equal ';    Case-1:        Echo ' $foo is bigger ';    Case 1:        echo ' $bar is bigger ';}

The values that are compared can be int, floating-point float, string, or even array. For more information on how different values compare to each other, see the documentation: Https://wiki.php.net/rfc/combined-comparison-operator

What's new in PHP 7

Of course, PHP 7 also brings new exciting features.

Scalar parameter types & return type hints

By adding these four scalar types: integer (int), floating-point (float), Boolean (bool), string, and possible parameter types, PHP 7 extends the parameter type declarations that were previously in the method (classes, interfaces, and arrays).

Further, we can optionally specify which types the methods and functions return. The supported types are bool,int,float,string,array,callable, class name or interface name, self and parent (for class methods).

Class calculator{    //We declare that the parameters provided is of type Integer public    function addtwoints (int $x , int $y): int {        return $x + $y;//We also explicitly say that this method would return an integer    }}

Type declarations help build stronger apps and avoid passing or returning incorrect values from a function. Other good things include static code analysis and an IDE that provides better code base hints when a document block is missing.

Since PHP is a weakly typed language, the values of parameters and return types are based on context projection. If you pass the value "3" in a function and declare the parameter type int, the interpreter will receive it as an integer without throwing any errors. If you do not want this, you can open strict mode by adding a declare indication.

Declare (Strict_types=1);

This is set on a per-file basis, as a global option to divide the code base into a global strict-open build and a global strict switch-off build, resulting in undesirable behavior when we merge the code from both.

Engine exception

By adding an engine exception, a fatal error caused by the Scripting terminal can be easily captured and processed.

For example, an error that calls a nonexistent method does not terminate the script, instead they throw an exception that can be handled by the try Catch block, which increases your application's error handling. This is important for such applications, services, and processes because a fatal error requires them to restart. The PHPUnit test will also become more usable because the entire test suite will be lost before the fatal error. exceptions, not errors, are handled on a per-test case basis.

PHP 7 looks and feels familiar, but it adjusts for performance. The refined Zend engine and the resulting performance have made a huge difference.

PHP 7 adds several new exception classes based on the type of error that may be triggered. To maintain compatibility between versions, a new interface Throwable is added, which can be implemented by both engine exceptions and user exceptions. In order to avoid engine exceptions extending the underlying exception class this is necessary, resulting in older code catching exceptions that were not yet there.

This will terminate the script with a fatal error before PHP 7:

try {    thisfunctiondoesnotevenexist ();} catch (\engineexception $e) {    //clean things up and log error    echo $e- >getmessage ();}

Anonymous class

Anonymous classes are cousins of anonymous functions that you can use in a short instance. Anonymous classes are simple to create and can be used just like a normal object. The following is an example from a document.

PHP 7 ago

Class MyLogger {public  function log ($msg) {    print_r ($msg. "\ n");}  } $pusher->setlogger (New MyLogger ());

Use anonymous classes:

$pusher->setlogger (new class {Public  function log ($msg) {    print_r ($msg. "\ n");}  );

Anonymous classes are useful in unit tests, especially when simulating test objects and services. This helps us to avoid heavyweight simulation libraries and frameworks by creating a simple object and providing the interfaces we want to simulate.

csprng function

Added two new functions that generate cryptographic secure strings and integers.

random_bytes (int $len);

Returns a random string of length $len.

Random_int (int $min, int $max);

Returns a number between $min and $max.

Unicode code point Escape syntax

Before PHP 7, unlike many other languages, PHP did not have a way to escape Unicode code points in the character language. This feature adds sequence \u to produce characters that use their UTF-8 code points. This is better than inserting characters directly, making it better to handle invisible characters and characters that have the same graphical display but different meanings.

echo "\u{1f602}"; Outputs??

Note that this will use \u to break the existing code because it alters the behavior.

Generator upgrade

The generator in PHP has also been given some elegant extra features. The generator now has a return declaration that can be used to follow the iteration to allow output of a final value. This can be used to detect that the generator has been executed without errors and allow calls to generated code to handle a large number of appropriate scenarios.

Further, the generator can return and yield expressions from other generators. This allows them to divide complex operations into simpler and more modular units.

function GenA () {    yield 2;    Yield 3;    Yield 4;} function Genb () {    yield 1;    Yield from GenA (); ' GenA ' gets called here and iterated over    yield 5;    Return ' success '; This is a final result we can check Later}foreach (Genb () as $val) {    echo "\ n $val";//This would output values 1 t o 5 in order} $genB ()->getreturn (); This should return ' success ' when there is no errors.

Expect

Expectations are an enhancement to assert () When backward compatibility is maintained. They allow assertions that consume 0 in production code and provide the ability to throw custom exceptions when an assertion fails, which is helpful in development.

ASSERT () becomes a language construct in PHP 7. Assertions should be used for debugging purposes only in development and test environments. In order to configure its behavior, two new titles were provided to us.

      • 1: Generate and execute code (development mode) (default)
      • 0: Generate code but jump around it at run time
      • -1: Do not generate code, 0 consumption (production mode)
      • 1: Thrown when an assertion fails, by throwing an object provided as an exception, or throwing a new Assertionerror object if the exception is not provided
      • 0: Use or generate a throwable as described above, but only generate a warning based on that object instead of throwing it (PHP 5 compatible)

Get ready to move PHP 5 to PHP 7.

This presentation introduces an opportunity to change/upgrade old features or even remove them if they are considered too old or obsolete for some time. Such a change would introduce a compatibility break in the old application.

Another problem with jumping from this version is that the important class libraries and frameworks you rely on may not have been upgraded to support the latest version. The PHP team has tried to make these new changes as backwards compatible as possible and to migrate to the new version with as little pain as possible. Newer and more continuously updated apps can find it easier to move to the new version, while older apps have to decide whether the benefits outweigh the costs and may choose not to upgrade.

Most interrupts are minor and can be easily migrated, while others may have more time to work harder. Basically, if you warn in your app before installing PHP 7, there's a good chance there will be a bug that interrupts the app until it's fixed. You've been warned, haven't you?

The old SAPI and the extension

Most importantly, such as MySQL extension (but you should not use this in the first place, right?). Such old and deprecated sapi have been removed. Full extensions and feature removal can be viewed here and here in this RfC.

In addition, other SAPI are being ported to PHP 7.

From PHP 7 A lot of old SAPI and extensions have been discarded. We were thinking that they should not be remembered.

Unified variable Syntax

This update makes some changes to the consistency of the variable-variable structure. This allows for more advanced expressions with variables but also introduces changes in some other scenarios, 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 interrupts the application's access to behaviors like these variables. On the other hand, you can do something wonderful like this:

Nested () foo () (); Calls The Return of foo () $foo->bar () ()//Iife syntax like JavaScript (function () {    //function body});//Nest Ed:: $foo:: $bar:: $baz

Old style tag removal

<%%>,<%= ...%> this type of on/off label has been removed and is no longer valid. It's easy to replace them with an effective one, but what do you do with them, geek?

Invalid names for classes, interfaces, and features

Because of additional items such as parameters and return types, classes, interfaces, and features no longer allow the following names:

    • bool
    • Int
    • Float
    • String
    • Null
    • True
    • False

The use of their existing applications and class libraries can cause interruptions, but the fix is easy. Similarly, although no errors are caused and are valid, the following should not be used because they are reserved for future use:

    • Resource
    • Object
    • Mixed
    • Numeric

Refrain from using them to keep you from making adjustments in the future.

For a complete list of changes that would interrupt compatibility, check out this document.

You can also use php7cc, which will check your code and can discover any potential problems that might come out if you go to PHP 7. But of course, there's no better way than to install PHP 7 and look at it yourself.

Potential PHP 7 compatibility issues

PHP 7 Infrastructure compatibility

A large number of hosted services have started to add support for PHP 7. This is good news for shared hosting vendors, because the resulting performance allows them to increase the number of site customers on existing hardware, reduce operating costs, and increase profitability. And for the client itself, they expect that under such conditions should not be much improved, but for the sake of fairness, shared hosting is not a performance-oriented option anyway.

On the other hand, services that provide virtual private providers or dedicated service providers can benefit from this performance leap. Some of the PAAs services that support PHP 7, such as Heroku, have been online earlier, but other services, like AWS Beanstalk and Oracle's OpenShift, are lagging behind. Check your PAAs vendor site to see if PHP 7 is already supported or is about to be supported.

Of course, IaaS allows you to take control of your hardware and install PHP 7 (or you can compile it if you like). PHP 7 packages for the mainstream IAAS environment are already available.

PHP 7 Software compatibility

In addition to infrastructure compatibility, you need to be aware of potential software compatibility issues. Popular Content Management Systems (CMS) such as Wordpress,joomla and Drupal have added support for PHP 7 in their latest version of LV. Mainstream frameworks such as Symfony and Laravel have also been well supported.

However, it is time to mention the word caution. This support does not extend to third-party code in the form of add-ons, plugins, packages, or whatever your CMS and framework call them. They may suffer from compatibility problems and make sure everything is ready for PHP 7 is your responsibility.

The Future of PHP

The release of PHP 7 removed old, outdated code and paved the way for new features and performance upgrades in the future. So PHP is expected to get more performance optimizations soon. Although there have been some compatibility interruptions in the past releases, most of the problems are easy to solve.

Class libraries and frameworks are now migrating to their code to PHP 7 so please get the latest version. I encourage you to try and see the results for yourself. Maybe your should be compatible and wait for use, and benefit from PHP 7.

Reference: Before debugging PHP that's not working, Consult this List of the ten most Common mistakes that PHP developers make
  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.