Home Backend Development PHP7 Introducing the new features and performance optimization of php7 and PHP5 comparison

Introducing the new features and performance optimization of php7 and PHP5 comparison

Mar 22, 2021 am 10:07 AM
php5 php7

Introducing the new features and performance optimization of php7 and PHP5 comparison

New features and performance optimizations compared between php7 and PHP5

1. Abstract syntax tree (AST) )

AST plays the role of a middleware in the PHP compilation process, replacing the original method of spitting out opcode directly from the interpreter, decoupling the interpreter (parser) and the compiler (compliler), which can reduce Some Hack code, at the same time, makes the implementation easier to understand and maintain

Recommended (free):PHP7

2. Natice TLS:

Thread data sharing security, open a global thread to use as data shared memory space

3. Specify parameter return value type

4. Changes in zval structure

5. Exception handling

PHP 5’s try...catch...finally cannot handle traditional Errors, you would usually consider hacking them with set_error_handler() if necessary. However, there are still many error types that cannot be caught by set_error_handler()

PHP 7 introduced the Throwable interface. Both errors and exceptions implement Throwable. Throwable cannot be implemented directly, but the \Exception and \Error classes can be extended. You can use Throwable to catch exceptions and errors. \Exception is the base class for all PHP and user exceptions; \Error is the base class for all internal PHP errors.

6. New parameter parsing method

7. Hashtable changes

buckets and Zvals no longer allocate memory separately. Eliminated a lot of useless redundancy.

8. Null Coalesce Operator

Directly to the example:

$name = $name ?? "NoName";  // 如果$name有值就取其值,否则设$name成"NoName"
Copy after login

9. Spaceship Operator Operator) (combined comparison operator)

Form: (expr) <=> (expr)

If the left operand is smaller, then - 1; if the left and right operands are equal, 0 is returned; if the left operand is larger, 1 is returned.

$name = ["Simen", "Suzy", "Cook", "Stella"];
usort($name, function ($left, $right) {
    return $left <=> $right;
});
print_r($name);
Copy after login

10. Constant Array

PHP 7 previously only allowed the use of constant arrays in classes/interfaces, but now PHP 7 also supports non-classes/interfaces An array of ordinary constants.

define("USER", [
  "name"  => "Simen",
  "sex"   => "Male",
  "age"   => "38",
  "skill" => ["PHP", "MySQL", "C"]
]);
// USER["skill"][2] = "C/C++";  // PHP Fatal error:  Cannot use temporary expression in write context in...
Copy after login

11. Unified variable syntax

$goo = [
    "bar" => [
        "baz" => 100,
        "cug" => 900
    ]
];

$foo = "goo";

$$foo["bar"]["baz"];  // 实际为:($$foo)[&#39;bar&#39;][&#39;baz&#39;]; PHP 5 中为:${$foo[&#39;bar&#39;][&#39;baz&#39;]};
                      // PHP 7 中一个笼统的判定规则是,由左向右结合。
Copy after login

12. Throwable interface

This is a worthwhile addition introduced by PHP 7 The anticipated new features will greatly enhance PHP's error handling capabilities. PHP 5's try ... catch ... finally can't handle traditional errors, so you'll usually consider hacking it with set_error_handler() if necessary. But there are still many error types that set_error_handler() cannot catch. PHP 7 introduces the Throwable interface. Errors and exceptions implement Throwable. Throwable cannot be implemented directly, but the \Exception and \Error classes can be extended. You can use Throwable to catch exceptions and errors. \Exception is the base class for all PHP and user exceptions; \Error is the base class for all internal PHP errors.

$name = "Tony";
try {
    $name = $name->method();
} catch (\Error $e) {
    echo "出错消息 --- ", $e->getMessage(), PHP_EOL;
}

try {
    $name = $name->method();
} catch (\Throwable $e) {
    echo "出错消息 --- ", $e->getMessage(), PHP_EOL;
}

try {
    intp(5, 0);
} catch (\pisionByZeroError $e) {
    echo "出错消息 --- ", $e->getMessage(), PHP_EOL;
}
Copy after login

13. Use combination statement

use combination statement can reduce the input redundancy of use.

use PHPGoodTaste\Utils\{
    Util,
    Form,
    Form\Validation,
    Form\Binding
};
Copy after login

14. Capture multiple types of exceptions/errors at one time

PHP 7.1 has added a new syntax for capturing multiple types of exceptions/errors - through vertical bars" |" to achieve.

try {
      throw new LengthException("LengthException");
    //   throw new pisionByZeroError("pisionByZeroError");
    //   throw new Exception("Exception");
} catch (\pisionByZeroError | \LengthException $e) {
    echo "出错消息 --- ", $e->getMessage(), PHP_EOL;
} catch (\Exception $e) {
    echo "出错消息 --- ", $e->getMessage(), PHP_EOL;
} finally {
    // ...
}
Copy after login

15. Changes in visibility modifiers

Class constants before PHP 7.1 are not allowed to add visibility modifiers. At this time, the visibility of class constants is equivalent To the public. PHP 7.1 adds visibility modifier support for class constants. In general, the usage range of visibility modifiers is as follows:

  • Function/method: public, private, protected, abstract, final
  • Class: abstract, final
  • Properties/variables: public, private, protected
  • Class constants: public, private, protected
class YourClass 
{
    const THE_OLD_STYLE_CONST = "One";

    public const THE_PUBLIC_CONST = "Two";
    private const THE_PRIVATE_CONST = "Three";
    protected const THE_PROTECTED_CONST = "Four";
}
Copy after login

iterable pseudo-type

PHP 7.1 introduced the iterable pseudo-type. The iterable type applies to arrays, generators, and objects that implement Traversable, which is a reserved class name in PHP.

$fn = function (iterable $it) : iterable {
    $result = [];
    foreach ($it as $value) {
        $result[] = $value + 1000;
    }
    return $result;
};

$fn([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
Copy after login

Nullable Type

PHP 7.1 introduces nullable types. Look at one of the gimmick features of the emerging Kotlin programming language is nullable types. PHP is becoming more and more like a "strongly typed language". For mandatory requirements of the same type, you can set whether it is nullable.

$fn = function (?int $in) {
    return $in ?? "NULL";
};

$fn(null);
$fn(5);
$fn();  // TypeError: Too few arguments to function {closure}(), 0 passed in ...
Copy after login

Void return type

PHP 7.1 introduced the Void return type.

function first(): void {
    // ...
}

function second(): void {
    // ...
    return;
}
Copy after login

The above is the detailed content of Introducing the new features and performance optimization of php7 and PHP5 comparison. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is the difference between php5 and php8 What is the difference between php5 and php8 Sep 25, 2023 pm 01:34 PM

The differences between php5 and php8 are in terms of performance, language structure, type system, error handling, asynchronous programming, standard library functions and security. Detailed introduction: 1. Performance improvement. Compared with PHP5, PHP8 has a huge improvement in performance. PHP8 introduces a JIT compiler, which can compile and optimize some high-frequency execution codes, thereby improving the running speed; 2. Improved language structure, PHP8 introduces some new language structures and functions. PHP8 supports named parameters, allowing developers to pass parameter names instead of parameter order, etc.

How to install mongo extension in php7.0 How to install mongo extension in php7.0 Nov 21, 2022 am 10:25 AM

How to install the mongo extension in php7.0: 1. Create the mongodb user group and user; 2. Download the mongodb source code package and place the source code package in the "/usr/local/src/" directory; 3. Enter "src/" directory; 4. Unzip the source code package; 5. Create the mongodb file directory; 6. Copy the files to the "mongodb/" directory; 7. Create the mongodb configuration file and modify the configuration.

What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? What should I do if the plug-in is installed in php7.0 but it still shows that it is not installed? Apr 02, 2024 pm 07:39 PM

To resolve the plugin not showing installed issue in PHP 7.0: Check the plugin configuration and enable the plugin. Restart PHP to apply configuration changes. Check the plugin file permissions to make sure they are correct. Install missing dependencies to ensure the plugin functions properly. If all other steps fail, rebuild PHP. Other possible causes include incompatible plugin versions, loading the wrong version, or PHP configuration issues.

How to solve the problem when php7 detects that the tcp port is not working How to solve the problem when php7 detects that the tcp port is not working Mar 22, 2023 am 09:30 AM

In php5, we can use the fsockopen() function to detect the TCP port. This function can be used to open a network connection and perform some network communication. But in php7, the fsockopen() function may encounter some problems, such as being unable to open the port, unable to connect to the server, etc. In order to solve this problem, we can use the socket_create() function and socket_connect() function to detect the TCP port.

How to change port 80 in php5 How to change port 80 in php5 Jul 24, 2023 pm 04:57 PM

How to change port 80 in php5: 1. Edit the port number in the Apache server configuration file; 2. Edit the PHP configuration file to ensure that PHP works on the new port; 3. Restart the Apache server, and the PHP application will start running on the new port. run on the port.

PHP Server Environment FAQ Guide: Quickly Solve Common Problems PHP Server Environment FAQ Guide: Quickly Solve Common Problems Apr 09, 2024 pm 01:33 PM

Common solutions for PHP server environments include ensuring that the correct PHP version is installed and that relevant files have been copied to the module directory. Disable SELinux temporarily or permanently. Check and configure PHP.ini to ensure that necessary extensions have been added and set up correctly. Start or restart the PHP-FPM service. Check the DNS settings for resolution issues.

How to install and deploy php7.0 How to install and deploy php7.0 Nov 30, 2022 am 09:56 AM

How to install and deploy php7.0: 1. Go to the PHP official website to download the installation version corresponding to the local system; 2. Extract the downloaded zip file to the specified directory; 3. Open the command line window and go to the "E:\php7" directory Just run the "php -v" command.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

See all articles