PHP 7.2 new features introduction

不言
Release: 2023-03-23 18:56:01
Original
3339 people have browsed it

The content of this article is about the introduction of the new features of PHP 7.2, which has certain reference value. Friends in need can refer to it

PHP 7.2 has been officially released on November 30, 2017 . This release includes new features, functionality, and optimizations to help us write better code. In this article, I will introduce some of the most interesting language features of PHP 7.2.

You can view the complete list of changes on the Requests For Comments page.

Core improvements

Parameter type declaration

Since PHP5, we can specify the expected declaration type of function parameters. If the wrong type of argument is passed, PHP will throw an error.

Parameter type declaration (also called type hint) specifies the parameter type expected to be passed to a function or class method.

Here is an example:

class MyClass {
    public $var = 'Hello World';
}$myclass = new MyClass;function test(MyClass $myclass){
    return $myclass->var;
}echo test($myclass);
Copy after login

In this code, the test function requires a MyClass instance. Incorrect parameter data types result in a fatal error.

Fatal error: Uncaught TypeError: Argument 1 passed to test() must be an instance of MyClass, string given, called in /app/index.php on line 12 and defined in /app/index.php:8
Copy after login

Since PHP 7.2 type hints can be used on object data, and this improvement allows generic object types to be used as parameters of a function or method. Here's an example:

class MyClass {
    public $var = '';
}class FirstChild extends MyClass {
    public $var = 'My name is Jim';
}class SecondChild extends MyClass {
    public $var = 'My name is John';
}$firstchild = new FirstChild;$secondchild = new SecondChild;function test(object $arg) {
    return $arg->var;
}echo test($firstchild);echo test($secondchild);
Copy after login

In the above example, we called the test function twice, passing a different object each time. This was unprecedented in previous versions of PHP.

PHP 7.2 new features introduction

Testing type hints for PHP 7.0 and PHP 7.2 in Docker.

Object return type declaration

If the variable type specifies the expected type of the function parameter, the return value type can also be specified as the expected type.

Return type declaration specifies the expected type that a function should return.

Since PHP 7.2, object data types can be declared using return types. Here’s an example:

class MyClass {
    public $var = 'Hello World';
}

$myclass = new MyClass;function test(MyClass $arg) : object {
    return $arg;
}

echo test($myclass)->var;
Copy after login

Previous PHP versions would throw the following fatal error:

Fatal error: Uncaught TypeError: Return value of test() must be an instance of object, instance of MyClass returned in /app/index.php:10
Copy after login

Of course, the PHP 7.2 code would print ‘Hello World’.

Parameter type generalization

PHP currently does not allow any difference in the parameter type of a subclass and its parent class or interface. What does it mean?
Refer to the following code:

<?phpclass MyClass {
    public function myFunction(array $myarray) { /* ... */ }
}class MyChildClass extends MyClass {
    public function myFunction($myarray) { /* ... */ }
}
Copy after login

Here we omit the parameter type in the subclass. In PHP 7.0, the following warning is produced:

Warning: Declaration of MyChildClass::myFunction($myarray) should be compatible with MyClass::myFunction(array $myarray) in %s on line 8
Copy after login

As of PHP 7.2, we can ignore types in subclasses without breaking any code. This solution allows us to upgrade a class in the library to use type hints without having to update all its subclasses.

Trailing commas in list syntax

Using a trailing comma on the last element of a PHP array is legal syntax, and is sometimes encouraged to easily avoid adding new elements. A missing comma error occurred. Since PHP 7.2 in grouping namespaces we can use trailing commas.

See Trailing Commas in List Syntax for a feel for the RFC and some sample code.

Security Improvements

Argon2 in Password Hashing

Argon2 is a powerful hashing algorithm that won the championship in the 2015 Password Hash Algorithm Competition. PHP 7.2 will As a replacement for the secure Bcrypt algorithm.
The new version of PHP has introduced the PASSWORD_ARGON2I constant, which can now be used in the password_* series of functions:

password_hash(&#39;password&#39;, PASSWORD_ARGON2I);
Copy after login

Unlike Bcrypt, which only uses one cost factor, Argon2 uses three cost factors to differentiate as follows:

  • Defines the amount of memory overhead in KiB that should be consumed during hash calculation (default is 1 << 10 or 1024 KiB or 1 MiB)

  • Define the time cost of the number of iterations of the hash algorithm (the default value is 2)

  • Parallel factor, used to set the number of parallel threads used in hash calculations (the default value is 2) )

The following three new constants define the default cost factors:

  • PASSWORD_ARGON2_DEFAULT_MEMORY_COST

  • PASSWORD_ARGON2_DEFAULT_TIME_COST

  • ##PASSWORD_ARGON2_DEFAULT_THREADS

Here is an example:

$options = [&#39;memory_cost&#39; => 1<<11, &#39;time_cost&#39; => 4, &#39;threads&#39; => 2];
password_hash(&#39;password&#39;, PASSWORD_ARGON2I, $options);
Copy after login
See Argon2 Password Hashing for more information.

Libsodium becomes part of PHP core

Starting with version 7.2, PHP includes the Sodium library in its core. Libsodium is a cross-platform and cross-language library for encryption, decryption, signing, password hashing, and more.

This library was previously provided through PECL.
For a list of Libsodium functions, see Quick Start.
See also PHP 7.2: The first programming language to add modern cryptography to its standard library.

Deprecation

Here is a list of deprecated functions and features for PHP 7.2, which will all be removed after PHP 8.0.

The

__autoload function in PHP 5.1 has been replaced by spl_autoload_register. A deprecation notice will now be reported during compilation.

When a fatal error is thrown, a

$php_errormsg local variable will be created. In PHP 7.2, error_get_last and error_clear_last should be used instead.

create_function() You can create a function with a function name and pass in the function parameters and function body as a list of the function. Because of security issues and poor performance, it is marked as deprecated and encapsulation is encouraged instead.

mbstring.func_overload Setting ini to a non-zero value has been marked as deprecated.

(unset) cast is an expression that always returns null and is useless.

If the second parameter is passed in, parse_str() will parse the query string into an array, otherwise it will parse into the local symbol table. For security reasons, it is not recommended to dynamically set variables in function scope, and using parse_str() without a second argument will throw a deprecation notice.

gmp_random() is platform dependent and will be deprecated. Use gmp_random_bits() and gmp_random_rage() instead.

each() Iterating over an array behaves very much like foreach(), but foreach() is a better choice for a few reasons, such as being 10 times faster. Using the former in a loop will now throw a deprecation prompt.

assert() The function checks the given assertion and performs related processing when the result is FALSE. assert() with a string parameter is now deprecated due to an RCE vulnerability. The zend.assertion ini option turns off assertion expressions.

$errcontext is an array containing local variables when an error occurs. It can be used as the last parameter of the error handler set_error_handler() function.

What does PHP 7.2 mean for WordPress users?

According to the official WordPress statistics page, as of this writing, only 19.8% of WordPress users have upgraded to PHP 7. Only 5% use PHP 7.1. You can see that more than 40% of users are still using PHP 5.6, and what’s even more frightening is that more than 39% of users are using a version of PHP that is no longer supported. As of December 2016, WordPress.org changed the official recommendation for users of PHP 5.6 to recommend using PHP 7 or above.
WordPress PHP 7.1 stats

WordPress PHP 7.1 Statistics

The above data performance is not pleasant, because it seems that PHP 7 seems to be faster. Here are some statistics:

  • PHP official benchmarks show that PHP 7 allows the system to perform 2 requests per second, which is almost just average latency compared to PHP 5.6.

  • Christian Vigh also published a PHP performance test comparison. He found that PHP 5.2 is nearly 400% slower than PHP 7.

We ran performance benchmarks PHP 5.6 vs PHP 7 vs HHVM in 2018. Similar to the benchmark above, we found that PHP 7.2 can perform almost three times the number of transactions (requests) per second compared to PHP 5.6.

WordPress benchmarks

WordPress Benchmark

  • WordPress 4.9.4 PHP 5.6 Benchmark Result: 49.18 req/sec

  • WordPress 4.9.4 PHP 7.0 Benchmark Result: 133.55 req/sec

  • WordPress 4.9.4 PHP 7.1 Benchmark Result: 134.24 req/sec

  • WordPress 4.9.4 PHP 7.2 Benchmark Result: 148.80 req/sec �

  • WordPress 4.9.4 HHVM Benchmark Result: 144.76 req/sec

Many things are slower to just update because of the time it takes to get involved in testing all new third-party plugins and themes to make sure they work properly. A lot of times, it's slow because they're not done yet. Not sure what version of PHP you're running? One of the easiest ways is to use the tool Pingdom or Google Chrome development tools. The first HTTP request header will usually display your version.

Check version of PHP

Check PHP version

This will rely on the host not modifying the value of the X-Powered-By header. If it is modified, you may not be able to see the PHP version information. In this case, you need to upload the PHP 7.2 new features introduction via FTP. Or you always ask the host.

Upgrade to PHP 7.2

PHP 7.2 is still partially unfinished, but you can try it out first. You can test your WordPress local site or check your scripts in a Docker-like environment, and you can test and compare different PHP versions from the command line.

Conclusion

Ready to switch to PHP 7.2? But at least hopefully you've transitioned to PHP 7 or higher first. If you're not ready to test it now, upgrade your scripts, review your code, and talk about your first experience with PHP 7.2.

Related recommendations:

Compile php7.2 under windows and extremely extended judy

How to install php7.2 on linux

CentOS7yum installation PHP7.2 instance method

The above is the detailed content of PHP 7.2 new features introduction. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template