PHP 7 Introduction: new features and Removed features

Source: Internet
Author: User
Tags what php
[Translation] PHP7 introduction: new features and removed features [Translation] PHP7 introduction: new features and Removed 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 news in 2015 was the release of PHP 7, which lasted 10 years from the last main version of PHP. After a huge step forward, PHP 7 introduced a large number of new features and performance upgrades.

However, due to some compatibility interruptions, it also removes old and obsolete features, which makes it more difficult to migrate old applications to new versions. If you plan to move an existing application to PHP 7 or build a new application, this guide should serve as a quick guide to what will happen.

But wait, where does PHP 6 go?

If you haven't been using PHP in your work recently, you may wonder what happened in PHP 6. Why did you jump directly from PHP 5 to PHP 7? Okay. In short, PHP 6 fails. Because PHP is mainly used for website development and the website requires Unicode, the main feature of version 6 is the local support for Unicode, so it makes sense to bring Unicode to PHP.

The idea is to bring full Unicode support to its core. In this way, we can bring the scalability to the language, from the ability to use funny emoji as variables and function names to the powerful internationalized character functions. For example, when another language is different from an English language that uses uppercase or lowercase letters, or when the name of a Chinese character needs to be converted to English.

PHP 6 is ambitious, but bad. This is why we ended the process with PHP 7 and skipped 6 directly.

Unfortunately, an ambitious plan proves to be a bigger problem than expected. Most code libraries need to be transplanted to support Unicode in both core and important extensions, which proves to be cumbersome and complex. This slows down the development of other features in the language and frustrated many PHP developers. The emergence of additional obstacles greatly reduced the interest in developing local Unicode support, which eventually led to the project being abandoned.

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

In any case, the past is hard to look back. let's take a look at what PHP 7 has brought.

Performance war, PHP 7 vs PHP 5

For almost all updates, minor performance upgrades are predictable. However, this time PHP has brought more important improvements than earlier versions, making pure performance the most attractive feature of PHP 7. This is part of the "PHPNG" project, which captures the internal structure of the Zend Engine itself.

By restructuring 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 seem very promising: the benchmark tests completed by real-world applications show that PHP 7 is twice faster on average than PHP 5.6 and reduces memory consumption by 50% during requests, this makes PHP 7 a powerful rival to the hhvm jit compiler. You can see the chart information drawn from Zend for some common CMS and framework.

PHP 7 seems familiar to me, but it makes adjustments to performance. The refined Zend engine and the resulting performance have undergone huge changes.

With the opportunity to build microservices around PHP, the reduction in memory consumption also enables smaller machines to better process requests. Internal changes, especially the AST implementation, also enable the possibility of pushing performance further to future optimization. A new internal JIT Implementation is being considered for future versions.

PHP 7 syntax sugar

PHP 7 comes with new syntax features. When you do not extend the functionality of the language itself, they provide a better or easier way to make your code more pleasant to write and look more comfortable.

Group import declaration

Now, we can simplify the imported Declaration group from the same namespace into a use row. This should help align declarations in a meaningful way or simply saving some bytes in the file section.

use Framework\Module\Foo;use Framework\Module\Bar;use Framework\Module\Baz;

We can use PHP 7:

use Framework\Module\{Foo, Bar, Baz};

Or, if you prefer the multi-line style:

use Framework\Module{    Foo,    Bar,    Baz};

Null merge operator

This solves a common problem in PHP programming, that is, when we want to assign the value of a variable to another variable, if the latter actually has settings, otherwise, a different value is provided for it. It is usually used when we process user input.

Before PHP 7:

if (isset($foo)) {    $bar = $foo;} else {    $bar = 'default'; // we would give $bar the value 'default' if $foo is NULL}

After PHP 7:

$bar = $foo ?? 'default';

You can also concatenate multiple variables as follows:

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

Ship operator

The spacecraft operator <=> allows three methods to compare two values, which not only means that they are equal, but also include which one is larger by returning an inequality of 1, 0 or-1.

We can make different actions based on different values:

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

The value can be an integer int, float, string, or even array. For more information about how different values are compared, see: https://wiki.php.net/rfc/combined-comparison-operator

New features in PHP 7

Of course, PHP 7 also brings new exciting features.

Scalar parameter type & Response type prompt

Add the following four scalar types: integer (int), floating point (float), Boolean (bool), string (string), and as much as possible parameter types, PHP 7 extends the parameter type declarations in methods (classes, interfaces, and arrays.

Furthermore, we can specify the types returned by methods and functions. Supported types include 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 are of type integer    public function addTwoInts(int $x, int $y): int {        return $x + $y; // We also explicitly say that this method will return an integer    }}

Type declarations help build stronger applications and avoid passing or returning incorrect values from functions. Others include static code analysis and IDE that provides better code library prompts when document blocks are missing.

Since PHP is a weak type language, the parameters and return type values are based on context projection. If the value "3" passed in a function and the declared parameter type is int, the interpreter will receive it as an integer without throwing any error. If you do not want this, add a declare command to enable strict mode.

declare(strict_types=1);

This setting is based on each file, and is used as a global option to divide the code library into a building with the global strictly enabled and built with the global strictly disabled, this results in unexpected behavior when we merge code from both.

Engine exception

By adding an engine exception, fatal errors caused by script terminals can be easily captured and processed.

For example, if you call an error that does not exist in a method, the script will not be terminated. Instead, they will throw an exception that can be processed by the try catch block, which improves the error handling of your application. This is important for applications, services, and processes because of fatal errors that require them to restart. PHPUNit testing will become more available because the entire test suite will be lost before a fatal error occurs. Exceptions, rather than errors, are handled based on each test case.

PHP 7 seems familiar to me, but it makes adjustments to performance. The refined Zend engine and the resulting performance have undergone huge changes.

PHP 7 adds several new exception classes based on the error types that may be triggered. To maintain compatibility between versions, a new interface Throwable is added, which can be implemented by engine exceptions and exceptions of users. In order to avoid engine exception expansion, basic exception classes are needed, resulting in older code capturing exceptions that were not found at the time.

Before PHP 7, the script will be terminated with a fatal error:

try {    thisFunctionDoesNotEvenExist();} catch (\EngineException $e) {    // Clean things up and log error    echo $e->getMessage();}

Anonymous class

An anonymous class is the table brother of an anonymous function. you can use it in a short instance. The anonymous class is easy to create and can be used as a normal object. The following is an example from the document.

Before PHP 7

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

Use anonymous class:

$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 avoid heavyweight simulated libraries and frameworks by creating a simple object and providing interfaces we want to simulate.

CSPRNG function

Added two new functions to generate encryption security strings and integers.

random_bytes(int $len);

Returns a random string with a length of $ 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 does not have a way to escape Unicode code points in character languages. This feature adds sequence \ u to generate characters that use their UTF-8 code points. In this way, it is better to insert characters directly, so that invisible characters can be better processed and characters with the same chart but different meanings can be displayed.

echo "\u{1F602}"; // outputs ??

Note that this will use \ u to disconnect the existing code because it changes the behavior.

Generator upgrade

The PHP generator also has some elegant and extra features. Now, the generator has a return statement that can be used to allow output of a final value after iteration. This can be used to detect scenarios where the generator has been executed without errors and the code generated can be called to process a large number of appropriate scenarios.

Furthermore, the generator can return and yield expressions from other generators. This allows them to divide complex operations into simpler and 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 will output values 1 to 5 in order}$genB()->getReturn(); // This should return 'success' when there are no errors.

Expected

It is expected to enhance assert () when maintaining backward compatibility. They allow zero-consumption assertions in production code and provide the ability to throw custom exceptions when the assertions fail, which is very helpful in development.

Assert () is a language structure in PHP 7. Assertions should only be used for debugging purposes in the development and test environments. In order to configure its behavior, two new titles are provided to us.

    • 1: generate and execute code (development mode) (default value)
    • 0: generate code, but jump around it at runtime
    • -1: no code generation, zero consumption (production mode)
    • 1: If an AssertionError object fails, a new AssertionError object is thrown by throwing an object that is provided as an exception or if the exception is not provided.
    • 0: use or generate a Throwable as described above, but only generate a warning based on that object rather than throw it (compatible with PHP 5)
Ready to move PHP 5 to PHP 7

The introduction of this main release brings about an opportunity to change/upgrade old features, or even remove them if they are considered too old or abandoned for a while. Such a change will introduce compatibility interruptions to old applications.

In addition, one problem caused by this version jump is that the important class libraries and frameworks you depend on may not be upgraded to the latest version. The PHP team has tried to make these new changes as backward compatible as possible and minimize the pain points of migrating to a new version. Updated and continuously updated applications can be found to be easier to move to the new version, while old applications have to decide whether the benefits are higher than the cost, and may choose not to upgrade.

Most of the interruptions are mild and can be easily migrated, while others may need more time to work harder. Basically, if you warn your application before installing PHP 7, the application may be interrupted until it is fixed. You have been warned, right?

Old SAPI and extensions

Most importantly, such as mysql extensions (but you should not use this in the first place, right ?) In this way, the old and obsolete SAPIs have been removed. For complete extensions and feature removal, you can view the RFC here and here.

In addition, other SAPIs are being transplanted to PHP 7.

Many old SAPIs and extensions have been discarded since PHP 7. We were wondering that they would never be remembered.

Unified Variable Syntax

This update made some modifications to the consistency of the variable structure. This allows more advanced expressions with variables, but also introduces changes in 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 will interrupt the application access behavior like these variables. On the other hand, you can do something amazing like this:

// Nested ()foo()(); // Calls the return of foo()$foo->bar()();// IIFE syntax like JavaScript(function() {    // Function body})();// Nested ::$foo::$bar::$baz

Remove old style labels

<%... %>, <% =... %>,

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.