Table of Contents
Core improvements
Parameter type declaration
Object return type declaration
Parameter type generalization
Trailing commas in list syntax
Security Improvements
Argon2 in Password Hashing
What does PHP 7.2 mean for WordPress users?
Upgrade to PHP 7.2
Conclusion
Home Backend Development PHP Tutorial PHP 7.2 new features introduction

PHP 7.2 new features introduction

May 24, 2018 pm 02:47 PM
php introduce new function

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!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles