Proposal: Dropping support for old PHP versions via a fixed schedule

While most people here will probably mostly know me as a (PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20) developer, I actually have a background in business studies, so when Matt Mullenweg reached out to me to continue the conversation about WordPress dropping support for older PHP versions in an in-person call, I decided to put my business acumen to use and see if I could come up with a proposal which would make sense from a business point of view for all parties involved, be it the amazing contributors to the WordPress project, the web hosts, the 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 builders, the web agencies and the users who often run their business via their WordPress website.

In short, I’m proposing a fixed schedule in which every PHP version is supported for five years. Additionally each WordPress release will receive security updates for four years. In effect, this means that users, at a stretch, would be able to run on one specific PHP version for nine years.

A fixed schedule will make this whole process transparent and will allow all parties to plan for the version drops accordingly.

With Matt’s blessing, I’m posting this proposal here on Make to gauge the reactions of the wider community to my idea.

Please feel very invited to leave a comment whether you agree with the proposal or not.
Mentioning what your involvement is with WordPress and how this proposal will impact you in a positive or negative way, would be very valuable input for further discussions on this.

Chicken vs egg

The situation we are currently in, is basically one of “Which came first, the chicken or the egg ?”.

Current situation: Classic Chicken vs Egg


WordPress doesn’t drop support for older PHP versions until enough users have moved over to newer PHP versions and a significant enough share of the WP users don’t upgrade their PHP version until they really have to because WordPress drops support for the version.

This is circular logic, which as most developers know, never ends well as you end up in an infinite loopLoop The Loop is PHP code used by WordPress to display posts. Using The Loop, WordPress processes each post to be displayed on the current page, and formats it according to how it matches specified criteria within The Loop tags. Any HTML or PHP code in the Loop will be processed on each post. https://codex.wordpress.org/The_Loop. where, in the end, neither moves forward.

So who are these users who don’t upgrade ?

Well, while we can’t know for sure, if we look at the figures, we can see some patterns:

Pie chart with the statistics for which version of WordPress is used by which percentage of users.
In the chart it is highlighted that there are 3.7% of users still on WP 5.1 (PHP stragglers), a whopping 10.6%on WP 4.9 (Gutenberg dislikers) and a similar percentage of users on WP versions older than WP 4.9, a  lot of which may be zombie-sites.

Take note of the fact that the percentage of users on WP 5.1 who didn’t upgrade yet is relatively small and only part of that can be attributed to the PHP < 5.6 version drop in WP 5.2.

So let’s look at some likely personas for users who don’t upgrade:

Image showing four persona's:
1. The zombie thinking "Huh, what notice ? what website ?"
2. The overwhelmed person thinking "Admin notices are so noisy, I just ignore them all".
3. The laid-back person thinking "No rush, I'll do it later (when it's needed)".
4. The business person thinking "We'll take the costs last minute and not a minute before".

We have the “zombie” persona, sites which are still online, but are not actively updated anymore.
These can be, for instance, sites which were linked to a specific event or other date-related topic which are still online for historical reasons, aggregate sites which automatically re-post from other sites without adminadmin (and super admin) involvement, or spam sites etc.

We have the “overwhelmed” persona, who blatantly ignores all admin notices. We all know why and how this happens. The multitude of notices in the admin area once a site has a few plugins and a theme installed trained this user to ignore them.

Then there is the “laid-back” persona, who has seen the notices, but doesn’t feel any urgency until they can’t update their site anymore.

And lastly, the “business” persona, often with a custom theme and a number of custom build plugins who’d rather move the costs of upgrading those to the next accounting year.

As for the user who feels out of their depth – amazing work has been done by the #site-health team to help those out.
For those users, I like to use the car analogy:

A website is something users will generally use regularly and expect to “just work”. So let’s make the comparison with something else a lot of people use regularly and expect to “just work”.

Say a car. Similar to WP, when one gets themselves a car, you need to familiarize yourself a little with how it works (interface/admin), but then it just runs. You put in petrol regularly (WP updates) to keep it running. Then once in a while, it needs a proper service. Now you have a choice: either you learn how to service a car yourself (read the site health materials and follow them up) or you go to a garage (hire a specialist) to do it for you.
And if you really don’t want to be bothered with all that, you lease a car instead (managed WP hosting solution).

Along the same lines: if you ignore the warning lights in a car (site health admin notices), you can’t pretend to be surprised that at some point it will break down (gets hackedhacked /can’t upgrade anymore). If was your responsibility as a user to act on them after all.

But Juliette, get to the point: how do you think we can get out of this situation ?

Ok, so here goes: I propose a fixed (rolling) schedule for dropping support for older PHP versions.

A fixed schedule means that such version bumps become predictable and with them becoming predictable, they become manageable and plannable.

These last two qualities are extremely important as all parties involved will know well in advance what they need to do and when it should be ready.

The current uncertainty over what WordPress will do leads to inaction, as we saw with two of the example personas, and we can counter that with becoming predictable and reliable with regards to the PHP version bumps.

So I propose that, as of now, we start dropping support for the PHP minor which is more than five years old each December, or if there is no release in December, in the WordPress release which is being worked on at that time.

That would currently look something like this, with the numbers at the top being the version of the WordPress release that December and the numbers at the bottom being the new minimum supported PHP version.

Timeline from December 2016 to December 2024 showing the WordPress version released that December and the minimum supported PHP version as of that WordPress version.
WordPress 5.6 in December 2020 would get a minimum of PHP 7.1.
WordPress 5.9 in December 2021 would get a minimum of PHP 7.2, etc
Below the timeline it shows for each PHP version when it was released and until when it will be supported by WordPress.

Keep in mind that, per the currently proposed schedule, the new minimum supported PHP version would always already be a version which is no longer actively supported by the PHP project, nor does it have security support anymore at the time it becomes the new minimum supported version for WordPress.

For example, PHP 7.1 was released in December 2016. Active support for PHP 7.1 stopped beginning of December 2018 and security support stopped on December 1, 2019. And based on the current proposal WordPress would still support it until December 2021.

But all those users on old WordPress versions…

Well, WordPress has always had a very liberal policy for backporting security fixes, so as part of this proposal, I’d like to suggest that the WordPress project makes a hard commitment to continuing to backportbackport A port is when code from one branch (or trunk) is merged into another branch or trunk. Some changes in WordPress point releases are the result of backporting code from trunk to the release branch. security fixes for WordPress versions up to four years back.

Timeline from December 2016 to December 2024 showing that during the lifetime of the upcoming WordPress 5.6 release, the 5.6 release would get active support, but that WordPress 4.7 (released December 2016) up to WordPress 5.5 (released this month) would get security releases (if needed).

What that would come down to in practice, is that if a user would always want to use the latest and greatest version of WordPress with the minimum of effort, they would need to ensure their PHP version is updated once every five years.

Slide: Example: user on PHP 7.4
* WordPress will offer 5 years of support for the PHP version.
* WordPress will offer 4 more years of security updates for WP versions before the version bump dropping PHP 7.4.
* In total this adds up to 9 years of support.

And if they don’t mind lagging behind a little in their WordPress version, they could even get away with only updating their PHP version once every nine years and still have their website running on a secure version of WordPress.

Now how does that sound ? Is that a liberal enough policy ?

Note: security fixes are currently back-ported as far back as WordPress 3.7. With this proposal, the minimum version of WordPress still receiving security fixes would not longer be a fixed version, but would change to a rolling number.

But what about the users currently on old WordPress versions ?

To solidify the commitment to making this as transparent as possible for the users, I propose we backport the PHP admin notice from the site-health project to the older, still currently security supported, WordPress versions, so that those users will be informed when they log in to their website.

Alongside of that we could ramp up the site-health notices based on this fixed schedule of version drops and committed security fix support.

Slide showing an "Urgency nudges" proposal:
* For websites running on a PHP versions no longer actively supported, an admin notice will be shown.
* As of six months before the planned drop of a PHP version, the admin notice on those sites would change colour to draw more attention to it.
* After the PHP version drop, the proposal is to show a big pop-up on admin login for the first and second year after. The notice is dismissable but will come back once a month.
* For the third and fourth year after support for the PHP version has been dropped, this pop-up will show every time an admin logs into the website.

So… what do you think ? I eagerly await the reactions of you all!

Props to @sergeybiryukov, @joostdevalk and @matt for looking this article over before publication.

#core, #core-php, #php, #request-for-comment

PHP related improvements & changes: WordPress 5.5 edition

As part of an ongoing effort to improve compatibility across all supported versions of PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 (currently 5.6.20–7.4), several tooling additions and improvements have been made during the 5.5 cycle.

A large handful of changes were made to address the findings from these tools. Below are some that you need to be aware of.

Automated PHP compatibility scanning

During the WordPress 5.3 cycle, a new job was added to Core’s Travis-CI builds to scan for potential PHP compatibility issues using the PHPCompatibilityWP PHPCS ruleset (see #46152). However, because the scan was reporting a large number of potential issues, it was placed in the allowed_failures list until each issue could be inspected and addressed.

During the 5.5 cycle, each potential issue was examined individually and either fixed, or manually marked as a false-positive.

As of [48046], the job performing a PHP compatibility scan has been removed from the allowed_failures list. 🎉

Now that this scan is not allowed to produce errors or warnings, potential PHP incompatibilities can be flagged and inspected immediately after being committed, ensuring they are never released to the world in WordPress.

In the future when the versions of PHP supported by WordPress change (in either direction), the configuration file can easily be adjusted to detect potential problems within the new range of supported versions.

For more information, see the related ticketticket Created for both bug reports and feature development on the bug tracker. on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. (#49922).

Deprecated: wp_unregister_GLOBALS()

The register_globals directive in PHP was deprecated in version 5.3 and removed entirely in 5.4. Because the first line of the function calls ini_get() (which returns false if the directive is not recognized), this function will always return early making it unnecessary.

The wp_unregister_GLOBALS() function is deprecated as of WordPress 5.5.

For more information, see the related ticket on Trac (#49938).

Deprecated: $HTTP_RAW_POST_DATA

The $HTTP_RAW_POST_DATA global variable was deprecated in PHP 5.6.0 and removed completely in PHP 7.0.0. Because of this, developers should not be relying the presence or accuracy of this variable. However, a search of the plugin directory for this variable still yields ~1,500 results. Although some of these matches are flagging $HTTP_RAW_POST_DATA within comments or in compatibility shims, developers should audit their code to remove this variable whenever possible.

Because PHP 5.6 is still supported and this variable is present in a large number of plugins, it will not be completely removed in WordPress 5.5. However, it will be removed from CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. when the supported versions of PHP is changed to PHP >= 7.0.

The following is the recommended replacement:

$var = file_get_contents( 'php://input' );

A few occurrences of this variable that did not affect the outcome of the code have been removed in 5.5. However, there are 2 instances that will remain because they were deemed particularly risky to remove before communicating the bad practice to the community.

  • xmplrpc.php (source)
  • wp-includes/rest-api/class-wp-rest-server.php (source)

For more information, refer to the related ticket on Trac (#49810).

Spread operator usage in the IXR library

In WordPress 5.3, the PHP spread operator was introduced throughout the code base. There are several benefits to utilizing the spread operator in addition to code modernization:

“Using the spread operator allowed for simplifying the code and improves performance – both in speed as well as memory use -, especially as it has been introduced in a number of functions which are used a multitude of times during every single pageload…”

WP 5.3: Introducing the spread operator by @jrf

The IXR library bundled with Core (now treated as an “adopted” library) powers XML-RPC related functionality in WordPress.

All func_get_args() calls within the IXR library’s code have now been updated to utilize the spread operator.

For more information, refer to the Trac ticket (#48267), the WP 5.3: Introducing the spread operator dev notedev note Each important change in WordPress Core is documented in a developers note, (usually called dev note). Good dev notes generally include: a description of the change; the decision that led to this change a description of how developers are supposed to work with that change. Dev notes are published on Make/Core blog during the beta phase of WordPress release cycle. Publishing dev notes is particularly important when plugin/theme authors and WordPress developers need to be aware of those changes.In general, all dev notes are compiled into a Field Guide at the beginning of the release candidate phase., or the Trac ticket that originally introduced the spread operator to Core (#47678).

Installing PHPUnit with Composer

Getting a local environment up and running for contributing to WordPress Core can sometimes be difficult, especially when running the PHPUnit test suite is desired. Different combinations of WordPress and PHP versions require different versions of PHPUnit.

Composer is a tool for dependency management in PHP. When project dependencies are specified, it will manage installing and updating those dependencies for you appropriately.

As of [47881], PHPUnit is now defined as a dev requirement in WordPress Core’s composer.json file.

Running composer install will determine the appropriate version of PHPUnit to install based on the PHP version Composer runs on.

For more information, refer to the Trac ticket (#46815).

Other Build/Test Tool improvements

  • Plugins and themes within src are now ignored when running Core linting locally. This will prevent coding standards violations from being flagged when developing locally using src instead of build (see #49781).
  • Previously, when the lint:php job ran on Travis-CI, the code was formatted using PHPCBF prior to linting. Since running composer format returns an error when changes are made, the linting part would not execute and a report would not be generated. Core will no longer run the formatting command prior to linting the code base for issues (see #49722).
  • The WordPress Coding Standards ruleset has been updated from version 2.1.1 to 2.3.0. For a full list of changes included in this update, read ruleset’s release notes (see #50258).
  • The recommended version of PHP specified in the readme.html file has been changed from 7.3 to 7.4. This brings the recommendation in line with the recommendations found on WordPress.org (see #50480)

Props @earnjam for review.

#5-5, #build-tools, #dev-notes, #php

Updating the Coding standards for modern PHP

Until May last year, contributions to WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. were bound to PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 5.2 syntax and most plugins and themes stuck to the PHP 5.2 minimum requirement as well.

However, with the change to PHP 5.6 as the minimum PHP version for WordPress Core, new PHP features have become available for use in WP Core and with the outlook of a minimum version of PHP 7.x in the (near) future, even more interesting language features will soon become available for use in WordPress Core, plugins and themes.

With that in mind, we’d like to define coding standards for a number of these constructs and propose to implement automated checking for these in the WordPress Coding Standards tooling in the near future.

While it may still be a while before some of these features will actually be adopted for use in WordPress Core, defining the coding standards in advance will allow for a consistent code base when they do get adopted and will allow for plugins and themes, which are not necessarily bound to the PHP 5.6 minimum, to safeguard their code consistency when they start using more modern PHP already.

To be honest, none of these proposals are terribly exciting and some may not even seem worth mentioning. Most follow either prior art in WordPress Core or industry standards for the same, but in the spirit of openness, we’d like to verify our take on these before implementing them.

Continue reading

#modernizewp, #codingstandards, #php, #wpcs

PHP Native JSON Extension Now Required

The PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 native JSONJSON JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML. extension has been bundled and compiled with PHP by default since 5.2.0 (2006). However, a significant number of PHP installs did not include it. In order to ensure a consistent experience for JSON related functionality in all supported versions of PHP, WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress. has historically included a large number of workarounds, functions, and polyfills.

In 2011 (WordPress 3.2), an attempt was made to remove JSON related compatibility code. However, it was discovered that a fair number of distributions were still missing the PHP JSON extension by default, and the removed code was restored to ensure compatibility.

In WordPress 5.2, the minimum version of PHP supported was raised from 5.2.6 to 5.6.20. In the 8 year period since the last attempt was made to encourage use of the PHP native JSON extension, the number of distributions with this extension disabled has significantly decreased.

Because of this, the PHP native JSON extension is now required to run WordPress 5.3 and higher.

To prevent compatibility issues, a site that does not have the PHP native JSON extension enabled will see an error message when attempting to upgrade to WordPress 5.3. The update will be cancelled and the site will remain on the current version (see [46455]). This is to prevent potential compatibility issues on servers running custom PHP configurations.

Here’s a summary of what has changed.

Deprecated

The following functions and classes will remain in the code base, but will trigger a deprecated warning when used (see [46205]):

  • The Services_JSON and Services_JSON_Error classes and all methods
  • The wp-includes/class-json.php file
  • The (private) _wp_json_prepare_data() function

Removed

The following functions, and classes have been removed entirely from the code base (see the [46208] changeset):

  • json_encode() function polyfill
  • json_decode() function polyfill
  • _json_decode_object_helper() function polyfill
  • json_last_error_msg() polyfill
  • JsonSerializable interface polyfill
  • $wp_json global variable
  • JSON_PRETTY_PRINT constant polyfill
  • JSON_ERROR_NONE constant polyfill

Unchanged

The wp_json_encode() function will remain with no intention to deprecate it at this time. This function includes an extra sanity check for JSON encoding data and should still be used as the preferred way to encode data into JSON.

For more information about these changes, check out #47699 on TracTrac An open source project by Edgewall Software that serves as a bug tracker and project management tool for WordPress. and the relevant changesets ([46205], [46206], [46208], [46377], and [46455]).

Props @jrf & @jorbin for peer review.

#5-3, #dev-notes, #php

WP 5.3: Introducing the spread operator

In WordPress 5.3, the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 5.6 spread operator has been introduced to WordPress in a number of places.

Using the spread operator allowed for simplifying the code and improves performance – both in speed as well as memory use -, especially as it has been introduced in a number of functions which are used a multitude of times during every single pageload, such as current_user_can() and add_query_arg().

For full details, see Trac ticket #47678.

Impact on plugins/themes

Most plugins and themes should see no impact of these patches, other than the improved performance.

However, if your 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/theme is one of the limited number of plugins and themes which extends one of the below listed classes and overloads any of the listed methods, you will need to take action.

What to do if your plugin/theme is affected

In nearly all cases, WP 5.3 has added a new parameter to the function signature using the spread operator. This allows for an easy transition as you can adjust the function signature of the method overloading it to do the same.
You may also want to adjust the code within the overloaded method to get the same performance benefits as the parent method.

See the relevant patches linked below for the full details of the change to each method and for inspiration.

Adding the extra argument will allow your plugin/theme to be compatible with both WP 5.3 and older WP versions, though it does raise the minimum PHP requirement for your plugin/theme to PHP 5.6.
Make sure you annotate this in the readme.txt!

In only one case – wpdb::prepare() -, WP 5.3 has changed an existing parameter.
In the exceptional situation that you would be overloading that method, you will need to make a choice whether you want to continue supporting older WP versions or to set the minimum WP version to WP 5.3.
If you set the minimum WP version to WP 5.3, you need to change the function signature of the overloading method to match the new function signature in WP 5.3 and you may also want to simplify some code in your method too.
If you want to continue to support older WP versions, you will need two versions of the class overload and an if/else toggle to load the correct one depending on the WP version being used.
Note: this really only applies to overloaded wpdb::prepare() methods. There is no need to do this if you overload any of the other affected methods.

What will break if I don’t make the change to my plugin/theme

Nothing. The world will keep turning as it did before.

You may get some complaints from end-users that they are seeing PHP warnings about a mismatched function signature in their PHP error logs, but other than that, all should still work as before.

This is not to say that you shouldn’t update your plugins/themes… You should.
It is just that if you don’t have time to do it right away, you don’t need to worry that your plugin/theme will be bringing sites down.

List of affected classes:

List of affected test classes:

#fortheloveofcode, #modernizewp, #5-3, #dev-notes, #php

PHP Coding Standards Changes

This is a follow-up to several changes proposed a few months ago.

While reading these changes, it’s important to keep in mind that they only apply to WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress.: you can (and should) choose practices that best suits your development style for your own plugins and themes. The coding standards are intentionally opinionated, and will always lean towards readability and accessibilityAccessibility Accessibility (commonly shortened to a11y) refers to the design of products, devices, services, or environments for people with disabilities. The concept of accessible design ensures both “direct access” (i.e. unassisted) and “indirect access” meaning compatibility with a person’s assistive technology (for example, computer screen readers). (https://en.wikipedia.org/wiki/Accessibility) over being able to use every possible language feature.

Closures (Anonymous Functions)

There was quite a lot of discussion around this proposal, particularly with regards to allowing closures as hook callbacks. Thank you everyone for your input, and for keeping disagreements respectful. 🙂

We do need a decision, however, and there were several key points that led to this:

  • It’s currently difficult to remove closures as hook callbacks. #46635 has several interesting proposals to address this in an entirely backward compatible manner.
  • While WordPress Core should strive to allow any callback to be unhooked, plugins have no such restriction.
  • The WordPress JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. Coding Standards allow for closures to be used, we should be aiming to bring the PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 standards in line with that.
  • The broader PHP world has embraced closures for many years, and have found ways to use them responsibly. We shouldn’t ignore PHP usage outside of WordPress.

With these points in mind, a conservative, but practical step is to allow closures as function callbacks, but not as hook callbacks in Core. Ultimately, we should be able to allow any sort of complex callback to be attached to hooksHooks In WordPress theme and development, hooks are functions that can be applied to an action or a Filter in WordPress. Actions are functions performed when a certain event occurs in WordPress. Filters allow you to modify certain functions. Arguments used to hook both filters and actions look the same., but the Core APIs aren’t quite ready for it yet.

Coding Standards Change

Where appropriate, closures may be used as an alternative to creating new functions to pass as callbacks.

Closures must not be passed as 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. or action callbacks, as they cannot be removed by remove_action() / remove_filter() (see #46635 for a proposal to address this).

Short Array Syntax

A little less controversial, but still with varying opinions, was the proposal to require short array syntax ( [ 1, 2, 3 ] ) instead of long array syntax ( array( 1, 2, 3 ) ) for declaring arrays.

While I’m personally partial to short array syntax, there were two particularly convincing arguments for using long array syntax:

  • It’s easier to distinguish from other forms of braces, particularly for those with vision difficulties.
  • It’s much more descriptive for beginners.

So, this change to the coding standards is the opposite of what was originally proposed, but is ultimately the more inclusive option.

Coding Standards Change

Arrays must be declared using long array syntax in WordPress Core.

Short Ternary Operator

The original proposal was to allow the short ternary operator, but this change reverses that. There’s a good argument that it looks too much like the null coalesce operator, especially as they perform different functions.

Take the following example from Core:

$height = isset( $data['height'] ) ? $data['height'] : 0;

It’s not possible to reduce this line with the short ternary operator, but it can be trivially reduced with the null coalesce operator:

$height = $data['height'] ?? 0;

The vast majority of other ternary operators in Core (which don’t have an isset() test) look something like this:

$class = $thumb ? ' class="has-media-icon"' : '';

This also can’t be reduced using the short ternary operator.

As the null coalesce operator is a useful addition (which we’ll be able to use once the minimum PHP version bumps to 7+), whereas the short ternary operator can only be used in a handful of cases in Core, it’s better to avoid the potential confusion, and not use the short ternary operator.

Coding Standards Change

The short ternary operator must not be used.

Assignments Within Conditionals

Particularly when there are multiple conditions, it can be quite difficult to spot assignments occurring in a conditional. This arguably falls under the Clever Code guidelines, but hasn’t been formalised.

I got a little ahead of myself with this one, and have already removed all assignments in conditionals from Core. Adding this change to the standard formalises the practice.

Coding Standards Change

Assignments within conditionals must not be used.

#php, #wpcs

Coding Standards Updates for PHP 5.6

With the minimum PHPPHP The web scripting language in which WordPress is primarily architected. WordPress requires PHP 5.6.20 version increasing to 5.6 as of WordPress 5.2, now’s a good time to be reviewing the WordPress Coding Standards.

Here is a set of changes that I’d like to propose.

Anonymous Functions (Closures)

Anonymous functions are a useful way to keep short logic blocks inline with a related function call. For example, this preg_replace_callback() call could be written like so:

$caption = preg_replace_callback(
	'/<[a-zA-Z0-9]+(?: [^<>]+>)*/',
	function ( $matches ) {
		return preg_replace( '/[\r\n\t]+/', ' ', $matches[0] );
	},
	$caption
);

This improves the readability of the codebase, as the developer doesn’t need to jump around the file to see what’s happening.

Coding Standards Proposal

Where the developer feels is appropriate, anonymous functions may be used as an alternative to creating new functions to pass as callbacks.

Anonymous functions must not be passed as 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. or action callbacks in WordPress CoreCore Core is the set of software required to run WordPress. The Core Development Team builds WordPress., as they cannot be removed by remove_action() / remove_filter() (see #46635 for a proposal to address this). Outside of Core, developers may pass anonymous functions as filter or action callbacks at their own discretion.

Namespaces

Namespaces are a neat way to encapsulate functionality, and are a common feature in modern PHP development practices. As we’ve discovered in the past, however, introducing namespaces to the WordPress codebase is a difficult problem, which will require careful architecture and implementation.

Side note: there’s currently no timeline for introducing namespaces to WordPress Core, expressions of interest are welcome. 🙂

Coding Standards Proposal

At this time, namespaces must not be used in WordPress Core.

Short Array Syntax

Rather than declaring arrays using the array( 1, 2, 3 ) syntax, they can now be shortened to [ 1, 2, 3 ]. This matches how arrays are declared in the WordPress JavaScriptJavaScript JavaScript or JS is an object-oriented computer programming language commonly used to create interactive effects within web browsers. WordPress makes extensive use of JS for a better user experience. While PHP is executed on the server, JS executes within a user’s browser. https://www.javascript.com/. Coding Standards.

To allow for plugins and themes that support older versions of WordPress, I’d like to propose that WordPress Core switches to short array syntax immediately, but plugins and themes may choose which they use. A future iteration would make short array syntax a requirement.

Coding Standards Proposal

Arrays must be declared using short array syntax in WordPress Core. Arrays may be declared using short array syntax outside of Core.

Short Ternary Syntax

A fairly common pattern when setting a variable’s value looks something like this:

$a = $b ? $b : $c;

The short ternary syntax allows this to be shortened, like so:

$a = $b ?: $c;

It’s important to note that this is different to the null coalesce operator, which was added in PHP 7. If $b is undefined, the short ternary syntax will emit a notice.

Coding Standards Proposal

Short ternary syntax may be used where appropriate.

Assignments within conditionals

While this isn’t directly related to the PHP version bump, I’d like to propose disallowing assignments within conditionals. Particularly when there are multiple conditions, it can be quite difficult to spot assignments occurring in a conditional. This arguably falls under the Clever Code guidelines, but hasn’t been formalised.

For example, this if statement would be written like so:

$sticky_posts = get_option( 'sticky_posts' );
if ( 'post' === $post_type && $sticky_posts ) {
	// ...
}

Coding Standards Proposal

Assignments within conditionals are not allowed.

Other New Features

Any other new features available in PHP 5.6 can be used, though we should continue to carefully consider their value and (in the case of newer PHP modules) availability on all hosts.


How do you feel about these changes? Are there other changes related to PHP 5.6 that you’d like to suggest?

#php, #wpcs