Backend Development

What’s New in PHP 8.6 Features?

What's New in PHP 8.6 Features?

PHP 8.6 was officially released on November 19, 2026, bringing several improvements to the language, including partial function application, a new clamp() function, duration handling, improved reflection APIs, better stream error handling, and more secure session defaults.

 

 

1. Partial Function Application

One of the most interesting additions in PHP 8.6 is Partial Function Application (PFA). Partial function application allows you to create a new callable from an existing function by providing some of its arguments in advance while leaving other arguments to be supplied later. PHP introduces the ? placeholder to indicate an argument that should be provided when the resulting closure is executed.

Consider this example for the array_find function:

$inputs = ['foo', '123', 'bar', '456'];

// Before PHP 8.6
$firstDigits = array_find($inputs, fn(string $v): bool => ctype_digit($v));

// With PHP 8.6 PFA
$firstDigits = array_find($inputs, ctype_digit(?)); // '123'

As you see how the PFA makes the code more short.

Here is what happens:

  • We use ? to indicate that the second argument will be provided later.
  • PHP creates a closure that accepts the remaining argument.

Another Example using the array_map function:

Previously you might write:

$names = ['JOHN', 'JANE', 'MICHAEL'];

$lowercaseNames = array_map(
    fn ($name) => strtolower($name),
    $names
);

With PHP 8.6 you can simplify this:

$lowercaseNames = array_map(
    strtolower(?),
    $names
);

You can also use the Partial Function Application with the Pipe operator:

$slug = 'Hello World'
    |> str_replace(' ', '-', ?)
    |> strtolower(...);

echo $slug;

 

2. Readonly Properties can have default values

PHP introduced readonly properties in PHP 8.1, allowing developers to prevent properties from being modified after initialization.

However, before PHP 8.6, readonly properties could not have default values.

For example, the following code was not allowed:

class Book
{
    public readonly string $title = 'PHP Guide';
}

PHP 8.6 removes this restriction.

You can now initialize readonly properties directly when declaring them:

class Book
{
    public readonly string $title = 'PHP Guide';
}

This becomes particularly useful for interfaces that define properties:

For example:

interface Migration
{
    public string $name { get; }
}

class CreateBooksTable implements Migration
{
    public readonly string $name = 'create_books_table';
}

 

3. The new clamp function

PHP 8.6 introduces a built-in clamp() function.

Its purpose is simple: ensure that a value stays within a specified minimum and maximum range.

Previously, developers commonly implemented this behavior using min() and max():

$value = 150;

$result = min(max($value, 0), 100);

echo $result;

// Output: 100

With PHP 8.6 you can simply write:

$value = 150;

$result = clamp($value, min: 0, max: 100);

echo $result;

// Output: 100

Here is how clamp works:

  • If $value falls within the bounds, it is returned unchanged;
  • otherwise, the nearest boundary ($min or $max) will be returned as in this example it returns 100.

Let’s look at a few more examples:

echo clamp(50, min: 0, max: 100);
// 50

echo clamp(150, min: 0, max: 100);
// 100

echo clamp(-10, min: 0, max: 100);
// 0

Using clamp with strings:

echo clamp('y', 'x', 'z');

// Output: y

echo clamp('a', 'x', 'z');

// Output: x

Using clamp with dates:

You can also use it with DateTime objects:

$startDate = new DateTimeImmutable('2026-01-01');
$endDate = new DateTimeImmutable('2026-12-31');

$date = new DateTimeImmutable('2025-01-01');

$result = clamp(
    value: $date,
    min: $startDate,
    max: $endDate
);

echo $result->format('Y-m-d');

// Output: 2026-01-01

Practical use cases:

  • Limiting pagination values.
  • Restricting discount percentages.
  • Validating user input ranges.
  • Keeping dates within a reporting period.

 

3. The new Time/Duration class

PHP 8.6 introduces a new Time\Duration class for representing a length of time. Previously, developers commonly represented durations using integers or floats:

$delay = 500; // Milliseconds

The problem is that the value itself doesn’t tell us which unit it represents.

Is it milliseconds, seconds, or minutes?

The new Duration class provides a more expressive and consistent way to work with durations.

Creating Durations:

use Time\Duration;

$oneSecond = Duration::fromSeconds(1);

$halfSecond = Duration::fromMilliseconds(500);

$fiveMinutes = Duration::fromMinutes(5);

Performing mathmatical operations:

You can add, subtract, multiply, and divide durations:

use Time\Duration;

$oneSecond = Duration::fromSeconds(1);

$halfSecond = $oneSecond->divideBy(2);

$total = $oneSecond->add($halfSecond);

Comparing Durations:

Comparison operators can be used with duration classes:

$shortDelay = Duration::fromMilliseconds(500);

$longDelay = Duration::fromSeconds(2);

if ($shortDelay < $longDelay) {
    echo 'The first delay is shorter.';
}

 

5. The new Polling API

PHP 8.6 introduces a new polling API under the Io\Poll namespace.

To understand why this matters, we first need to understand the problem it addresses.

When building applications that handle multiple network connections, servers need a way to monitor several streams and determine which ones are ready for reading or writing.

Previously, PHP developers commonly relied on stream_select() for this purpose.

PHP 8.6 introduces a more unified API that can use platform-specific polling mechanisms, such as:

  • epoll on Linux.
  • kqueue on BSD and macOS.
  • Event ports on Solaris.
  • WSAPoll on Windows.

Although you may not using the Polling API directly, but it may be used in packages such as ReactPHP, however understanding how to use it is useful.

Creating a Polling context:

use Io\Poll\Context;
use Io\Poll\Event;
use Io\Poll\StreamPollHandle;
use Time\Duration;

// Create a polling context
$context = new Context();

// Create a non-blocking server socket
$server = stream_socket_server(
    'tcp://0.0.0.0:8080',
    $errno,
    $errstr
);

stream_set_blocking($server, false);

// Wrap the stream
$handle = new StreamPollHandle($server);

// Register the stream for read events
$context->add(
    $handle,
    [Event::Read],
    ['type' => 'server']
);

// Wait for events
while (true) {
    $watchers = $context->wait(
        Duration::fromSeconds(1)
    );

    foreach ($watchers as $watcher) {
        // Handle triggered events here
    }
}

The polling context monitors registered streams and returns information about events that have occurred.

Does this mean PHP now supports asynchronous programming?

Not exactly.

The new polling API does not introduce a built-in event loop or a complete asynchronous programming model.

Instead, it provides a lower-level mechanism for monitoring I/O events.

Libraries and frameworks such as ReactPHP and Amp can potentially use this API to build more efficient event loops and asynchronous runtimes.

It also provides benefits internally to PHP itself, particularly for PHP-FPM and signal handling in thread-safe builds.

 

6. Improved Reflection API

PHP 8.6 extends the Reflection API with two new methods:

ReflectionProperty::isReadable()

ReflectionProperty::isWritable()

These methods allow developers to determine whether a property can be read or written from a particular scope.

This is particularly useful following the introduction of readonly properties and asymmetric property visibility in previous PHP versions.

Consider the following class:

class Book
{
    public function __construct(
        public private(set) string $title
    ) {}
}

The property is publicly readable, but only the class itself can modify it.

We can inspect this behavior using reflection:

$property = new ReflectionProperty(
    Book::class,
    'title'
);

var_dump($property->isReadable(null));
// true

var_dump($property->isWritable(null));
// false

var_dump($property->isWritable(Book::class));
// true

The first argument specifies the scope from which the property is being accessed.

Passing null represents global scope.

You can also provide an object as the second argument:

class Book
{
    public readonly string $title;
}

$book = new Book();

$property = new ReflectionProperty(
    Book::class,
    'title'
);

var_dump(
    $property->isWritable(null, $book)
);
// true

$book->title = 'PHP 8.6 Guide';

var_dump(
    $property->isWritable(null, $book)
);
// false

 

7. DocComments for function parameters

PHP 8.6 allows developers to place documentation comments directly on function parameters.

Previously, you would normally document parameters using a PHPDoc block above the function:

/**
 * @param Book[] $books
 */
function store(array $books): void
{
    // Store books
}

With PHP 8.6 you can move the comment directly to the parameters:

function store(
    /** @param Book[] */
    array $books
): void {
    // Store books
}

You can document multiple parameters individually:

function search(
    /** Search query */
    string $query,

    /** Maximum number of results */
    int $limit = 10
): array {
    // Search implementation
}

You can retrieve these doc comments using the Reflection API:

$reflection = new ReflectionFunction('search');

$parameters = $reflection->getParameters();

echo $parameters[0]->getDocComment();

 

8. The new SortDirection Enum

PHP 8.6 introduces a built-in SortDirection enum to represent sorting directions. Previously, libraries and frameworks often implemented their own sorting constants or enums.

enum SortDirection
{
    case Ascending;
    case Descending;
}

For examples:

$direction = SortDirection::Descending;

A framework or library can accept this enum in it’s sorting methods:

$query->orderBy(
    'created_at',
    SortDirection::Descending
);

 

9. __debuginfo() method in Enums

PHP 8.6 allows enums to implement the __debugInfo() magic method.

This method controls the information displayed when an object is inspected using var_dump().

For example:

enum Status: int
{
    case OK = 200;
    case NOT_FOUND = 404;
    case FOUND = 302;

    public function __debugInfo(): array
    {
        return [
            __CLASS__ . '::' . $this->name . ' = ' . $this->value
        ];
    }
}

Now when you execute:

var_dump(Status::OK);

PHP uses your custom debug information.

 

10. cookie and session improvements

Three PHP session configuration defaults have changed to provide better security out of the box.

Configuration Previous default PHP 8.6 default
session.use_strict_mode 0 1
session.cookie_httponly 0 1
session.cookie_samesite Unset Lax

Let’s understand what these changes mean.

session.use_strict_mode

When enabled, PHP rejects session IDs that have not been properly initialized by the session handler. This helps protect applications against session fixation attacks.

session.cookie_httponly

When enabled, the browser prevents JavaScript from accessing the session cookie through document.cookie. This reduces the risk of session cookie theft through client-side scripts.

session.cookie_samesite

The new default is Lax. This helps protect against certain cross-site request scenarios by restricting when browsers send session cookies with cross-site requests.

 

11. Some deprecations in PHP 8.6

Returning from a finally block

Returning from a finally block is now deprecated.

For example:

function getConfig(): array
{
    try {
        return loadConfig();
    } finally {
        return [];
    }
}

This is problematic because the return statement inside finally can override the original return value and even suppress an exception.

Deprecated type-checking functions

Some older aliases for type-checking functions are deprecated.

Deprecated Recommended alternative
is_double() is_float()
is_integer() is_int()
is_long() is_int()
doubleval() floatval()

Other deprecated functionality

Other notable deprecations include:

  • strcoll() and the SORT_LOCALE_STRING sorting flag.
  • spl_classes(), in favor of ReflectionExtension::getClassNames().
  • metaphone().
  • mysqli_get_charset() and mysqli::get_charset().
  • mysqli::stmt_init(), in favor of mysqli::prepare().
  • CSV-specific methods on SplFileObject.
  • Several inherited sorting and serialization methods on ArrayIterator.
  • Passing objects where certain functions expect arrays.
  • Using let or is as identifiers.
  • Using readonly as a function name.
0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted