PHP 8 and WordPress Compatibility: Everything You Need to Know
If you’re a developer or you follow web development trends, you’re probably aware that a new, major update to PHP was released late last year. You may be wondering if it’s a good idea to upgrade your website to this new version.
PHP 8 brings lots of fresh features and changes, as well as the promise of big performance improvements. However, major version updates sometimes introduce compatibility issues with WordPress core and WordPress plugins, so the answer isn’t necessarily clear-cut.
In this article, we’ll explore the biggest features and changes in PHP 8, and give advice on when (and if) you should upgrade. Let’s dig in!
An Introduction to PHP 8
PHP 8, the latest version of the popular scripting language, was released at the end of November 2020. If you’re not familiar with PHP, it’s one of the main programming languages used both in platforms like WordPress and across much of the web. In fact, most of the core parts of WordPress are written in PHP.
PHP 8 brings a huge number of changes to the language when compared to the current version (7.4). There are also new functions and features, like the Just-In-Time (JIT) compiler, as well as updates to attributes and error handling. You can check out the full list of changes for all the details.
Of course, like any major PHP update, this one may also contain ‘breaking changes’, code updates that aren’t compatible with software built using older versions of PHP. PHP 7 was no different in this regard. For that reason, it’s smart to exercise some caution and do plenty of research and testing before updating.
We’ll look into all these details in a bit. First, however, let’s explore some of the new features in PHP 8.
8 Changes to Know About in PHP 8
As with any major release, PHP 8 contains a collection of new and updated features, as well as some behind-the-scenes bug fixes and changes. Here, we’ll cover some of the most interesting and exciting updates.
1. Significant Performance Improvements
Perhaps the most hyped and anticipated change in PHP 8 is in the realm of performance – particularly in the form of the Just-In-Time (JIT) compiler. In layman’s terms, a compiler takes the source code (in PHP) and turns it into something readable by the computers executing the code.
The difference with a JIT compiler is that it does this only as needed, during ‘run time’ rather than beforehand. The aim is to be more efficient and provide faster performance, and the JIT compiler in PHP 8 seems to deliver on that promise.
Unfortunately, the speed and efficiency improvements to PHP as a whole from the JIT compiler may not translate directly to a huge boost in WordPress performance. While you may notice a slight bump in speed, WordPress depends on more than just PHP to function: there are also elements like JavaScript in play that won’t benefit from these changes.
Still, it’s a step in the right direction, and one that ultimately paves the way for future changes to increase WordPress performance. It’s also going to be a big boon to developers working with PHP code in other contexts.
2. New PHP Functions
Performance improvements aren’t the only thing that’s exciting about PHP 8. There are also several all-new functions that make searching easier and more convenient:
str_contains
is a new function designed to make searching for a ‘needle’ inside a given string of code (the haystack in this analogy) simpler and less error-prone. In prior PHP versions, strstr
and strpos
were the functions used for this, but they require more complex code blocks and have some issues.
The new function looks like this:
str_contains ( string $haystack , string $needle ) : bool
If the ‘haystack’ contains the ‘needle’, it returns a true/false message, which can be customized. Pretty simple!
str_starts_with()
and str_ends_with()
are also new functions intended to simplify searching within strings. These are more specific, however: they simply look to see if the string either starts or ends with the given term and return a true/false response. This is a commonly-needed function in PHP, so its inclusion is welcome.
Finally, get_debug_type
is a function that returns the type of a specified variable. PHP already has a similar function in the form of gettype
, but the new option is intended to be more useful for developers and can also resolve class names.
3. The Introduction of Named Parameters
PHP 8 now supports Named Parameters, rather than simply positional parameters. If that leaves you scratching your head, don’t worry: we’ll explain.
Essentially, positional parameters require your code to place the parameters in the same order as the function you’re calling. On the other hand, named parameters can be placed in any order, since the code recognizes their names and not just their positions. To use the str_contains
function from above as an example, positional parameters would look like this:
function str_contains(string $haystack, string needle): bool {}
str_contains('FooBar', 'Foo');
Whereas named parameters would look like this:
function str_contains(string $haystack, string $needle): bool {}
str_contains(haystack: 'FooBar', needle: 'Foo');
What that means in practice is that with named parameters, both of these pieces of code would be correct and return the same result:
str_contains(haystack: 'FooBar', needle: 'Foo');
str_contains(needle: 'Foo', haystack: 'FooBar');
For seasoned developers, this enables increased readability with certain functions, whereas those new to development get a bit more forgiveness if they forget the order of operations for a given function.
Finally, named parameters use the default values if they’re not explicitly called in the code. This means you can skip optional parameters that don’t require deviation from the default. This is not possible with positional parameters.
4. Attributes v2
PHP 8 introduces Attributes v2. This expands and improves on the attributes system in PHP, and promises to bring it more in line with other languages.
Attributes are a form of ‘structured metadata’ for classes, properties, functions, and more. They enable developers to define configuration directives directly in the code. In previous versions of PHP, attributes came in the form of ‘doc-comments’, which are simple strings that lack structure and aren’t parsed automatically.
Attributes are added before the declaration they belong to, but can be declared either before or after a doc-comment that documents them. See this example from the PHP wiki:
<<ExampleAttribute>>
class Foo
{
<<ExampleAttribute>>
public const FOO = 'foo';
<<ExampleAttribute>>
public $x;
<<ExampleAttribute>>
public function foo(<<ExampleAttribute>> $bar) { }
}
$object = new <<ExampleAttribute>> class () { };
<<ExampleAttribute>>
function f1() { }
$f2 = <<ExampleAttribute>> function () { };
$f3 = <<ExampleAttribute>> fn () => 1;
These new attributes will help streamline a process that is already used by PHP developers in a more convoluted way, and should also help standardize attributes across developers.
5. Improved Error Handling
Another big change in the newest version of PHP is in the realm of error handling. In PHP 8, internal functions now throw exceptions on ‘type’ errors. This is a major improvement that is, unfortunately, not backward-compatible with old code. However, it will make debugging errors much simpler in the future.
In older versions, PHP would simply return null when it found a value it can’t use, like in this example:
var_dump(strlen(new stdClass));
// Warning: strlen() expects parameter 1 to be string, object given
// NULL
This isn’t useful at all, and worse, it’s not consistent across functions. PHP 8 will provide developers with a clearer picture to help them troubleshoot these errors and get things working. The new standard format is:
declare(strict_types=1);
var_dump(strlen(new stdClass));
// TypeError: strlen() expects parameter 1 to be string, object given
This standardized behavior should be a big boon for developers.
6. Arrays Starting With a Negative Index
In previous versions of PHP, when an array started with a negative index, the following indices would start with 0. Consider this example code:
$a = array_fill(-5, 4, true);
var_dump($a);
In older versions of PHP, this would give the following output:
array(4) {
[-5]=>
bool(true)
[0]=>
bool(true)
[1]=>
bool(true)
[2]=>
bool(true)
}
As you can see, the numbers jump immediately from -5 to 0, skipping everything in between – which is not terribly useful. Of course, if you know this is the expected behavior, then you can prepare for it. If you’re new to the language or not familiar with this functionality, however, it can be pretty confusing.
In PHP 8, this changes. Now, the next index will be one more than the starting index, regardless of whether it’s positive or negative. Here’s the output of the same code in PHP 8:
array(4) {
[-5]=>
bool(true)
[-4]=>
bool(true)
[-3]=>
bool(true)
[-2]=>
bool(true)
}
It’s important to note that this change is not backward compatible. Therefore, code that relies on or expects the behavior from previous PHP versions will need to be updated for the new index handling.
7. Weak Maps
PHP 8 introduces a new class: WeakMap
. This class takes the existing support for weak references (added in PHP 7.4) and expands it into a much more useful form.
According to the PHP Wiki, weak maps “allow creating a map from objects to arbitrary values (similar to SplObjectStorage) without preventing the objects that are used as keys from being garbage collected”. In the event that an object key is garbage collected, it’s removed from the map.
Although support for weak references was added in PHP 7.4, it was less useful than it could have been because weak references by themselves aren’t particularly common. They almost always appear in the context of a weak map.
Additionally, the way the weak references were implemented in PHP 7.4 made simply adding a weak map feature impossible. For this reason, the entire feature was scrapped and rewritten for PHP 8, and the result should be much more useful for developers.
8. Saner Numeric Strings
PHP makes use of what’s known as ‘numeric strings’, which are strings that can be interpreted as numbers by the language. In past versions of PHP, there were three categories for strings that contain numbers:
- Numeric strings
- Leading-numeric strings
- Non-numeric strings
The first two categories count as numeric strings, but they were treated differently depending on which operation was being performed. This isn’t entirely intuitive, and unless you were aware of these differences, you might get some unexpected results.
In PHP 8, these categories have been unified into a single concept. According to the official documentation: “Numeric characters only with both leading and trailing whitespace are allowed. Any other type of string is non-numeric and will throw TypeErrors when used in a numeric context.”
This results in a much simpler system behind the scenes. It also helps to make expected outcomes clearer for developers, so overall this is a welcome change.
PHP 8 and WordPress Compatibility
Since WordPress (and its plugins) depend so heavily on PHP, new versions of the language can result in compatibility issues if other software hasn’t been updated. This is particularly true for major version releases, such as PHP 8.
Typically, WordPress releases its own new versions to coincide with these major PHP updates, in order to help ensure a smooth transition. The latest version of WordPress, 5.6, is designed to fulfill this role. However, WordPress has stated that version 5.6 should only be considered ‘beta-compatible’ at this time.
What this means is that WordPress 5.6 should be compatible with PHP 8, and the developers have done fairly extensive testing on this front. There is still the risk of undiscovered issues with WordPress core, however, so the developers can’t guarantee yet that everything will work perfectly.
What’s more, this update only applies to WordPress core. Plugins and themes by third-party developers will need to be updated separately, a process that can take some time.
What does that mean for you? First, if you’re considering updating, you’ll want to double-check that the theme and plugins you use are certified as compatible by their developers.
It’s also a good idea to do a trial run of major updates on a test server before implementing them in your live environment. PHP 8 is no different – it should be tested thoroughly.
Testing can be done in a staging environment created through your hosting account, or you can create a local copy of your site using tools like XAMPP, MAMP, and Local. Each of these solutions enables you to create a copy of your site directly on your computer.
This lets you perform whatever tests and configuration changes you need without impacting your live site at all. Most tools enable you to create as many local installations as you like, so they’re a fantastic way to try out new things.
Finally, you should only consider updating at this time if there’s a feature in PHP 8 that you absolutely can’t live without. The previous version, PHP 7.4, will still receive active support until November 28, 2021, and it will receive security updates for another year after that.
This means that you don’t need to update until the end of 2022. Take your time, test thoroughly, and update only when you’re sure your site will operate smoothly with the new version.
How to Update Your Version of PHP
If you’re eager to get your hands on PHP 8, either for testing or for a live environment, A2 Hosting makes it easy. First, you’ll need to access your cPanel. To do so, log into your A2 Hosting account. This admin area enables you to manage everything related to your domains and websites:
Locate the domain you want to update and click on cPanel Login:
From there, scroll down to the Software section and click on Select PHP Version:
This tool enable you to easily edit your PHP version, extensions, and settings from one place. To change the version, just click the drop-down menu at the top of the page and choose the one you want to update to:
You can also switch to an older version of PHP if you like. If you need more help, check out the full instructions in our knowledge base.
If you’re on a different hosting provider, there’s a chance that they offer a similar tool. Your best bet is to consult with your provider’s documentation or contact support.
Conclusion
PHP 8 brings significant performance improvements and new features to the popular scripting language. The new JIT Compiler in particular has been the source of much excitement and seems to live up to the hype.
However, keep in mind that the latest version of WordPress, 5.6, is only ‘beta compatible’ with PHP 8. It may be a good idea to hold off if your site is a critical part of a business. Meanwhile, you can try it out on a testing site to learn more about what it has to offer.
To ensure that you’re always running the latest and greatest software, including PHP 8, be sure to check out our WordPress hosting plans. There’s something for every need and budget!
Image credit: geralt.