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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles