WordPress and PHP 8.0


Update on November 24, 2020: Added a call out in the “Strict type/value validations for internal functions” section that there are still scenarios where WP CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. could potentially pass invalidinvalid A resolution on the bug tracker (and generally common in software development, sometimes also notabug) that indicates the ticket is not a bug, is a support request, or is generally invalid. types to PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 or higher core functions, especially where values are passed through filters. Props @hellofromtonya.


PHP 8.0 is in the final stages of its release cycle. As of the publish date of this post, version 8.0 RC5 has been released, and the final release of PHP 8.0.0 is scheduled for November 26, 2020.

As the expected changes in PHP 8 were made known earlier this year, WordPress Core contributorsCore Contributors Core contributors are those who have worked on a release of WordPress, by creating the functions or finding and patching bugs. These contributions are done through Trac. https://core.trac.wordpress.org. worked to identify potential compatibility issues within the code base. This includes a call to test earlier in the release cycle.

WordPress Core aims to be compatible with PHP 8.0 in the 5.6 release (currently scheduled for December 8, 2020).

However, PHP 8.0 is a major version update with a large number of changes that break backwards compatibility, and many features that were deprecated within the PHP 7.x feature releases have been officially removed.

What does compatibility mean here?

Significant effort has been put towards making WordPress 5.6 compatible with PHP 8 on its own, but it is very likely that there are still undiscovered issues remaining.

Because of the nature of WordPress usage and the commitment to our user base, compatibility is to be considered in the eyes of those users. The goal is to elevate the broader ecosystem to a state that is compatible with PHP 8. That requires that the Core software not just be compatible on its own, but also provides defenses against common problems seen in the transition to PHP 8, while continuing to function on older versions of PHP.

It also should be acknowledged that WordPress is never used in isolation (without any theme or plugins), so WordPress itself being able to run on PHP 8 does not indicate “full” compatibility.

The state of PHP 8 support within the broader ecosystem (plugins, themes, etc.) is impossible to know. For that reason, WordPress 5.6 should be considered “betaBeta A pre-release of software that is given out to a large group of users to trial under real conditions. Beta versions have gone through alpha testing in-house and are generally fairly close in look, feel and function to the final product; however, design changes often occur as part of the process. compatible” with PHP 8.

“Beta compatibility”

Calling WordPress 5.6 “beta compatible” is a good first step. Doing so acknowledges the hard work that has been done to get WordPress running on PHP 8 without major issues and achieve passing PHPUnit tests. It also honors the project’s commitment to being compatible with the new versions of PHP when they are released.

At the same time Core cannot claim “full compatibility” because the process to achieve that state takes a larger amount of time within the greater ecosystem. That’s where WordPress Core needs help.

All pluginPlugin A plugin is a piece of software containing a group of functions that can be added to a WordPress website. They can extend functionality or add new features to your WordPress websites. WordPress plugins are written in the PHP programming language and integrate seamlessly with WordPress. These can be free in the WordPress.org Plugin Directory https://wordpress.org/plugins/ or can be cost-based plugin from a third-party and theme developers, as well as hosting communities, are called on to make their code compatible with PHP 8. This will allow WordPress to attain truly “full compatibility” sooner, and without end users having to carry the burden.

It’s also worth noting that all known compatibility issues that were identified through automated testing or static analysis have been addressed, except those detailed further down in this post. Automated test coverage of WordPress Core needs much improvement, and some problems will require manual testing of WordPress on PHP 8 under varying conditions to discover.

For the reasons above, it is highly recommended that you thoroughly test your site before upgrading to PHP 8.


Below is a breakdown of why the PHP 8 update is a bit different than other more recent PHP updates, and the changes that directly affect WordPress in PHP 8.0 that developers need to be aware of.

PHP release types

The release process that the PHP project currently follows was proposed and established back in 2010. This process outlines strict guidelines around when certain types of changes can be made. The process is structured around the idea of “major releases”, and follows semantic versioning.

The current major release of PHP is 7. Over the last 5 years, there have been 4 feature releases for the PHP 7 major releasemajor release A release, identified by the first two numbers (3.6), which is the focus of a full release cycle and feature development. WordPress uses decimaling count for major release versions, so 2.8, 2.9, 3.0, and 3.1 are sequential and comparable in scope. (7.1, 7.2, 7.3, and 7.4), and over 130 security/bug fix releases to these feature releases.

Feature releases

Though new features and bugbug A bug is an error or unexpected result. Performance improvements, code optimization, and are considered enhancements, not defects. After feature freeze, only bugs are dealt with, with regressions (adverse changes from the previous version) being the highest priority. fixes are allowed in feature releases, backwards compatibility and APIAPI An API or Application Programming Interface is a software intermediary that allows programs to interact with each other and share data in limited, clearly defined ways. compatibility must be maintained. These rules dictating what types of changes are allowed, lower the likelihood that sites will break when upgrading to new feature releases within the same major release of PHP.

When older features are deprecated within these releases, they remain functional. It’s common practice for deprecated features to trigger errors (usually E_WARNING, E_NOTICE, or E_DEPRECATED level), informing developers that the feature is deprecated. Deprecated features can only be removed in a future major release.

Major releases

Like feature releases, bug fixes and new features can be added in major releases. However, old features can be removed entirely, maintaining backwards compatibility and API compatibility is not required.

As of PHP 8 RC4, there are 48 changes to core PHP that break backwards compatibility, and 166 throughout PHP 8 overall (extensions, libraries, etc.).

What this means for developers

Sites that are consistently updating to the latest versions of PHP and addressing issues with each feature release are usually less likely to experience problems when updating to a new major version.

New features in PHP 8 are not compatible with PHP 7 or PHP 5 and usually cause fatal errors.

While making your plugin or theme PHP 8 compatible is strongly encouraged, using features added in PHP 8 is not recommended in distributed plugins and themes unless Requires PHP is set to 8.0 in the headerHeader The header of your site is typically the first thing people will experience. The masthead or header art located across the top of your page is part of the look and feel of your website. It can influence a visitor’s opinion about your content and you/ your organization’s brand. It may also look different on different screen sizes. section of the main file (plugins) or style.css file (themes).

Changes in PHP 8

Below is a non-exhaustive breakdown of select changes in PHP 8.0 that plugin and theme developers need to be aware of and should accommodate in their code.

Named parameters

PHP 8 introduces the ability to pass arguments to a function by the parameter name instead of the parameter position. This is advantageous in several ways, but to name a few:

  • The argument’s meaning becomes self documenting.
  • The arguments become order-independent.
  • Default values can be skipped arbitrarily.

As an example, let’s take a look at retrieving a term as an associative array using get_term().

<?php
// PHP < 8.0
$my_term = get_term( 1, '', ARRAY_A );

// PHP >= 8.0
$my_term = get_term( output: ARRAY_A, term: 1 );

Note that the arguments in the second example are defined out of order, and because the arguments are not processed in order, the optional parameters using the default value, are no longer required.

Named parameters also work with PHP’s internal functions.

<?php
// Using positional arguments:
array_fill( 0, 100, 50 );

// Using named arguments:
array_fill( start_index: 0, count: 100, value: 50 );

This is a very simplistic overview of the named parameters feature. Please read the full Request for Comments (RFC) on the PHP website for a complete breakdown, which details the impact on variadic functions, func_get_args() and related functions, as well as call_user_func_array() and related functions.

Named parameters and WordPress

The named parameter feature introduces a significant backwards compatibility consideration for all PHP code going forward. With the introduction of this feature, parameter names become a part of the API contract and any changes to their names in future WordPress releases will break backwards compatibility, causing a fatal error when code is invoking a function using an outdated parameter name.

An active review of the function signatures throughout WordPress Core has been proposed to ensure that all parameter names are descriptive, accurate, and do not use reserved keywords to avoid any potential for confusion, but it will not be a part of WordPress 5.6.

Using named parameters when calling WordPress functions and class methods is explicitly not supported and highly discouraged until this audit can be completed, as during the audit, parameter names are subject to change without notice. When this audit has been completed, it will be announced in a future developer note.

If you choose to take advantage of named parameters when using WordPress Core functions and classes before that time, you do so at your own risk.

Additionally, PHP Core has been reviewing their own parameter names in anticipation of the PHP 8 release. Because the PHP documentation has not yet been updated to reflect PHP 8 changes, some of the parameter names currently detailed in the documentation may also change.

To follow or contribute to this review, see #51553, and #50531 on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress..

Strict type/value validations for internal functions

When support for scalar type declarations was added in PHP 7.0, a new (optional) per-file directive to enforce strict type checking was also added. Including declare( strict_types = 1 ); at the top of a file would ensure that strict type checking is performed on all arguments and return values where scalar types were declared.

When configured, strict type checking also extends to extensions and internal PHP functions invoked within the file. In strict mode, when the type of a value passed does not match the type expected, a Fatal error: Uncaught TypeError is triggered.

However, when strict type checking was not enabled, the behavior of internal functions when receiving an unexpected type was very inconsistent. Some threw a warning and returned NULL, some returned false and threw a TypeError with strict types on, and others generated a TypeError (even if strict_types was not declared).

Starting in PHP 8, a TypeError will be consistently thrown for all internal PHP functions when invalid parameter types are passed, even when strict type checking is not declared.

Additionally, some PHP core functions which did not have type declarations previously, now do. It’s likely that some TypeErrors will be thrown for functions which didn’t even give a warning in older PHP versions.

Type checking for user-defined functions will remain the same. Including declare( strict_types = 1 ); at the top of files is required to enforce strict type checking throughout the file. No WordPress Core code uses strict mode.

An effort to ensure defensive code practices are in place to avoid any potential for invalid types to be passed to WordPress Core function is underway in #51423. Until this is completed, it is possible that some code within WordPress could trigger a TypeError, especially if a value’s type is incorrectly changed through code hooked to a filterFilter Filters are one of the two types of Hooks https://codex.wordpress.org/Plugin_API/Hooks. They provide a way for functions to modify data of other functions. They are the counterpart to Actions. Unlike Actions, filters are meant to work in an isolated manner, and should never have side effects such as affecting global variables and output..

Please read the full RFC on the PHP wiki for a complete breakdown of these changes. For more information on this as it relates to WordPress Core, see #51525 on Trac.

Stricter type checks for arithmetic and bitwise operators

In past versions of PHP, applying arithmetic and bitwise operators to arrays, non-overloaded objects, and resources was allowed. However, the behavior was sometimes inconsistent in different scenarios.

Starting in PHP 8, all arithmetic and bitwise operators will throw a TypeError when one of the operands is an array, non-overloaded object, or resource. An exception to this is array + array, which will remain unchanged.

Please read the full RFC on the PHP wiki for a complete breakdown of these changes. For more information on this as it relates to WordPress Core, see #51525 on Trac.

Saner numeric strings

Numeric string handling has been altered to be more intuitive and less
error-prone. Trailing white space is now allowed in numeric strings for
consistency with how leading white space is treated. This mostly affects:

  • The is_numeric() function
  • String-to-string comparisons
  • Type declarations
  • Increment and decrement operations

The concept of a “leading-numeric string” has been mostly dropped; the cases where this remains exist in order to ease migrationMigration Moving the code, database and media files for a website site from one server to another. Most typically done when changing hosting companies.. Strings which emitted an E_NOTICE “A non well-formed numeric value encountered” will now emit an E_WARNING “A non-numeric value encountered” and all strings which emitted an E_WARNING “A non-numeric value encountered” will now throw a TypeError. This mostly affects:

  • Arithmetic operations
  • Bitwise operations

This E_WARNING to TypeError change also affects the E_WARNING “Illegal string offset ‘string'” for illegal string offsets. The behavior of explicit casts to int/float from strings has not been changed.

Please read the full RFC on the PHP wiki for a complete breakdown of these changes.

Non-strict comparisons between numbers and non-numeric strings

Non-strict comparisons between numbers and non-numeric strings now work by casting the number to string and comparing the strings. Comparisons between numbers and numeric strings continue to work as before. Notably, this means that 0 == "not-a-number" is considered false now.

A few other code patterns that may be common in plugins and themes that will be affected:

  • '' < 0 is now considered true (see [48960]).
  • 'not-a-number' > 0 is also now considered true (see [49043]).

Error, warning, and notice changes

A large handful of preexisting errors have been reclassified. Here’s are some that may be commonly encountered:

Warnings converted to error exceptions

  • Attempting to write to a property of a non-object. Previously this
    implicitly created a stdClass object for null, false and empty strings.
  • Attempting to append an element to an array for which the PHP_INT_MAX key is already used.
  • Attempting to use an invalid type (array or object) as an array key or
    string offset.
  • Attempting to write to an array index of a scalar value.
  • Attempting to unpack a non-array/Traversable.

Please read the full RFC on the PHP wiki for more information on these changes.

Notices converted to warnings

  • Attempting to read an undefined variable.
  • Attempting to read an undefined property.
  • Attempting to read an undefined array key.
  • Attempting to read a property of a non-object.
  • Attempting to access an array index of a non-array.
  • Attempting to convert an array to string.
  • Attempting to use a resource as an array key.
  • Attempting to use null, a boolean, or a float as a string offset.
  • Attempting to read an out-of-bounds string offset.
  • Attempting to assign an empty string to a string offset.

Read the full RFC on the PHP wiki for more information.

Build & Test Tool Related Changes

Because WordPress supports PHP 5.6.20 or higher, running the WordPress Core PHPUnit test suite on PHP 8 is not straightforward.

  • PHPUnit >= 9.3 is the only version of PHPUnit that currently supports PHP 8.
  • PHPunit 5.7.x is the last version to include support for PHP 5.6.
  • PHPUnit 8.x changed several methods that do not return values to specify a void return type declaration. However, this return type is not available in PHP < 7.1.

In order to maintain the ability to run the test suite on PHP 5.6 while also allowing the tests to run on PHP 8, the changes to PHPUnit required have been backported into the WordPress Core test suite and Composer is used to manipulate the autoload process for PHPUnit 7.x.

To run the WordPress Core PHPUnit test suite on PHP 8, it is required to use Composer for installation and running.

To help make this easier, a new NPM script has been added to run the test suite within the local Docker environment using the Composer installed version of PHPUnit.

// Run within the local Docker container using version of
// PHPUnit installed within the container.
npm run test:php

// Run within the local Docker container using version of
// PHPUnit installed via Composer.
npm run test:php-composer

For more information on this new command, see #51456. For more information on making the test suite compatible with PHP 8/PHPUnit >= 8, see #46149, #50902, and #50913.

External Libraries

Several external libraries bundled with WordPress Core have been updated to fix PHP 8 compatibility issues. Pull requests have been opened where appropriate to ensure these changes are included in future releases of these libraries.

  • SimplePie has been updated from version 1.5.5 to 1.5.6 (see #51521). Additionally, the WP_Feed_Cache class has been deprecated and will only be loaded for backwards compatibility if SimplePie < 3 is loaded within a plugin (see #51629 and #29204).
  • sodium_compat was updated to avoid an error when attempting to access the MB_OVERLOAD_STRING constant, which has been removed in PHP 8 (see #51399).
  • Text_Diff was updated to fix a “Non-static method cannot be called statically” fatal error (see #51559).

Additional notes

  • create_function() has been removed. The final instance of this function in WordPress has been removed (see #50899).
  • The @ operator will no longer silence fatal errors. Care should be taken that error messages are not displayed in production environments, which can result in information leaks.
  • Following the hash comment operator # immediately with an opening bracket is not supported as a comment anymore since this syntax is now used for attributes.
  • libxml_disable_entity_loader() has been deprecated (see #50898).
  • Resource to object return type changes, including the introduction of the is_gd_image() function.
  • Changes to sorting: if any code relied on a certain sort order based on previous behavior, this may now fail.
  • The parameter/return types for various PHP functions have changed and may have an impact. Subtle changes like that substr() will now always return a string. Previously, this returned string|false.

Summary

As always, reading through the complete upgrade document is highly recommended.

Even as WordPress Core continues to expand its support for new versions of PHP, support for old versions will remain as is for the time being, staying at PHP 5.6.20 and higher until usage numbers show that the impact on users will be minimal.

There is a separate initiative to decrease the usage numbers for older versions of PHP being guided by the Core PHP team through the servehappy initiative. If you wish to help with this effort, please join the #core-php room in the Making WordPress Core Slack instance.

WordPress continues to encourage all users to run the latest and greatest versions of PHP. This includes PHP 8.0 upon its official release.

A full list of tickets related to PHP 8.0 support can be found on Trac.

Props @helen, @jrf, @jeffpaul, @sergeybiryukov, @andraganescu, @omarreiss, @hellofromtonya, and @chanthaboune for peer reviewing.

#5-6, #dev-notes, #php-8-0