A new PHP release is rolling out to servers worldwide after developers of the open-source scripting language launched version 8.6 this week.

Fixed on the calendar for November since PHP 8.4 in 2024, these updates pack new features and clean up a few bugs. Usually, the bugs are benign enough not to require a mid-year patch, but the path to version 8.6 included a real doozy: a pair of PHP vulnerabilities now known as PHP2Shell.

Discovered with the help of AI tools, the PHP2Shell security holes could have opened doors for attackers and have existed in the PHP system since the release of version 5.4 in 2012. Patches for the vulnerabilities across various PHP versions became available in late October. By then, the PHP Group had already shared the third release candidate for version 8.6.

Release candidate four solved the PHP2Shell problem in 8.6 on October 21, while smaller fixes kept development going until November 11 and release candidate seven — now PHP 8.6.

With that security issue behind us, let’s focus on the more visible changes found in 8.6.

New features and improvements in PHP 8.6

A Time\Duration class

The new Duration class in PHP 8.6 brings a stopwatch-like feel to time math, without the baggage of calendar/clock measurement complicated by months with differing numbers of days, daylight saving time, and time zones.

Duration here can be measured in nanoseconds, and with values equal to more than 9.2 billion seconds available on 64-bit systems, it’s handy to be able to manipulate these numbers without being surprised by floating-point imprecision.

// Sleep for half a second 
$half = \Time\Duration::fromMilliseconds(500);  
time_nanosleep($half->seconds, $half->nanoseconds);

In addition to the method for capturing milliseconds illustrated above, you’ll also find these basic methods:

  • fromNanoseconds()
  • fromMicroseconds()
  • fromSeconds()
  • fromMinutes()
  • fromHours()

Methods for performing a variety of calculations on these values are built in. Here are two examples:

// Subtract
$remaining = \Time\Duration::fromSeconds(10)->sub(\Time\Duration::fromMilliseconds(2500));
show('10 s - 2.5 s', $remaining);
// Output: 10 s - 2.5 s: 7.500000000 

// Multiply
$total = \Time\Duration::fromMilliseconds(1500)->multiplyBy(4);
show('1.5 s × 4', $total);
// Output: 1.5 s × 4: 6.000000000

A new math function: clamp()

Just like C++, Java, Rust, Ruby — and even CSS — PHP now has a clamp() function that evaluates a value within a range defined by minimum and maximum parameters.

If the value you are testing falls within the minimum and maximum limits, the function returns that value. Otherwise, it returns whichever of the minimum and maximum values is closest.

Some examples:

// “min:” and “max:” notation is optional
echo clamp(5, min: 1, max: 10); // 5 - Within range
echo clamp(15, 1, 10); // 10 - Closest to 15

// Doesn’t have to be numbers
clamp("b", "a", "c") // "b"

The function can even compare the values you will work with in the Duration class above.

Partial function application

It looks like a function call, but using ? and/or ... as placeholders makes it a closure. The function is actually called when the remaining parameters are provided:

$replaceWhitespace = str_replace(' ', ?, ?);
echo $replaceWhitespace('+', ' Hello World ');
// Output: +Hello+World+

Below, we can be more efficient with the pipe operator, which requires a function with a one-parameter callable on the right.

echo ' Hello-World '
    |> trim(...) // This line already works since PHP 8.5
    |> str_replace('-', ' ', ?)
    |> strtoupper(...)
    |> str_pad(?, 13, '!', STR_PAD_BOTH);

// Output: !HELLO WORLD!

Readonly property defaults

Readonly properties were introduced in PHP 8.1 and were designed to be initialized once at runtime and then never change. Providing a default value for a readonly property didn’t seem to make sense when constants already served that role.

But PHP 8.4 brought property hooks, which made it possible to declare properties in interfaces. PHP 8.6 makes it easier to implement get-only interface properties with fixed values without having to assign them in a constructor.

Here’s a popular example used to illustrate the new approach:

interface Question {
    public int $answer { get; }
}

class UltimateQuestion implements Question {
    public readonly int $answer = 42;  // Fatal error before PHP 8.6
}

DocComments for function parameters

PHP 8.6 lets code-writers add DocComments alongside function and method parameter declarations, rather than listing @params in a block above. In addition, you can read the comments with the new ReflectionParameter::getDocComment() method.

Here’s an example of how DocComments might have been handled before:

class Staff
{
    /**
     * Returns employee details when name and department ID match
     *
     * @param string $name       Employee name
     * @param int    $department Department ID
     */
    public function search(string $name, int $department): array
    {
        return [];
    }
}

Now this is possible:

class Staff
{
    /**
     * Returns employee details when name and department ID match
     */
    public function search(
        /** Employee name */
        string $name,
        /** Department ID */
        int $department
    ): array {
        return [];
    }
}

var_dump(
    new ReflectionParameter([Staff::class, 'search'], 'name')
        ->getDocComment(),
);
// string(20) "/** Employee name */"

One enum to sort them all

If you’ve used many of PHP’s built-in sorting functions, you know that parameters used to control the direction (ascending or descending) of a sort are a mixed bag. The functions array_multisort() and scandir() use differently named integer constants. Then there are the strings “ASC” and “DESC” for some uses, and the function rsort() just to do the reverse of sort().

New in the PHP 8.6 global namespace is a SortDirection enum that could be used to bring some order to the problem. The enum is defined like this:

enum SortDirection {
    case Ascending;
    case Descending;
}

But here’s the thing: None of PHP’s built-in sorting functions support these as parameters (yet). For now, know they are there for your custom sorting code and for third-party library developers.

A mysqli::quote_string() method

For users of the MySQL Improved Extension (mysqli), a new mysqli::quote_string() method escapes a string and wraps it in quotes, just like PDO::quote().

The new method works much like mysqli::real_escape_string(), except that the returned value is wrapped in single quotes and should have no additional quotes applied before inserting into a database.

Here’s an example from the new method’s documentation using a string (a city name) with troublesome punctuation:

$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");

$city = "'s-Hertogenbosch";
$query = sprintf("SELECT CountryCode FROM City WHERE name=%s", mysqli_quote_string($mysqli, $city));

#[\Override] for class constants

You can now apply the #[\Override] attribute to class constants as you can to methods and properties. You’d do this to override the same-named element of a parent class or implements a method, property, or class constant defined in an interface.

Here’s an example from the new official documentation:

class Base {
    protected const FOO = 'foo';
}

final class Extended extends Base {
    #[\Override]
    protected const BOO = 'boo';
}

Deprecations in the new PHP release

New PHP releases usually include functionality flagged for removal in future versions. These deprecated features are typically removed in major updates, which, for most of the deprecations in recent years, will come with the release of 9.0

These are some of the more notable deprecated elements announced with the release of PHP 8.6:

What’s in a name? Maybe lots

Starting with this latest PHP release, you’ll be discouraged from using the word namespace as a class constant and from declaring a function with the name readonly.

These uses are now deprecated so that they will be available in the future as reserved keywords.

The same goes for using let or is as an identifier for elements such as the name of a class, interface, trait, enum, function, or constant.

When PHP 8.5 was released, non-canonical cast names, like boolean, integer, double, and binary, were deprecated in favor of bool, int, float, and string, respectively. In 8.6, this has expanded to include some function aliases. Eventually, PHP users will need to replace any occurrences of the names on the left below with those on the right:

  • is_double() — is_float()
  • is_long() — is_int()
  • is_integer() — is_int()
  • doubleval() — floatval()

Changes in the MBString extension

Most PHP developers are familiar with the Multibyte String (mbstring) extension, which supports manipulating text in various character encodings.

However, nearly a dozen functions under the mbstring umbrella have been deprecated, all of them related to regular expressions and code no longer maintained in the Oniguruma library (mbregex).

The functions have names like mb_ereg_replace() and mb_ereg_search(), but also include mb_split().

In preparation for the removal of these functions in PHP 9.0, users are being directed to the Perl-compatible regular expressions library.

Backward incompatible changes

Deprecations generally go unnoticed when your code executes, unless you’re a fan of verbose error logs. But some changes could cause noticeable errors in certain edge cases.

For example, many functions will now throw a ValueError for out-of-range values, invalid flags, or strings containing NUL bytes, instead of silently truncating or ignoring them.

You can review these backward-incompatible changes on the official PHP website.

Get ready for PHP 8.6

Any new PHP release encompasses hundreds of changes. You can find a complete list of PHP 8.6 updates in the PHP Group’s official GitHub repository.

Here at Kinsta, we’re working to make PHP 8.6 available to our WordPress hosting customers. Once it’s live, you’ll be able to switch to the new release using our PHP settings tools.

We recommend trying any new PHP release in a staging environment before moving it to a live site.

Steve Bonisteel Kinsta

Steve Bonisteel is a Technical Editor at Kinsta who began his writing career as a print journalist, chasing ambulances and fire trucks. He has been covering Internet-related technology since the late 1990s.