PHP 8.6 Released: Partial Functions, Time\Duration, clamp(), and 10 More Features
PHP 8.6 introduces partial function application with placeholder syntax, a native Time\Duration class, clamp() for range constraints, enum debugInfo, precise JSON error locations, native I/O polling, SortDirection enum, URI builder, and multiple performance optimizations.
1. Partial Function Application
PHP 8.6 adds partial function application using the ? placeholder. When a function is called with ? in place of an argument, PHP returns a closure waiting for the missing parameter.
$startsWithAdmin = str_starts_with(?, 'admin.');
array_filter(['admin.users', 'web.home', 'admin.posts'], $startsWithAdmin);
// Result: ['admin.users', 'admin.posts']This eliminates verbose arrow functions in collection pipelines. Variadic placeholders ( ...) are also supported, simplifying pipeline and functional programming patterns.
2. Time\Duration Class
A native, strongly-typed Time\Duration class represents time quantities with built-in units, removing the need to pass raw numbers (seconds, milliseconds) throughout code.
use Time\Duration;
$timeout = Duration::fromSeconds(30);
$cacheTtl = Duration::fromHours(2);
$total = $timeout->add(Duration::fromMilliseconds(500));
$isLonger = $timeout->compare($cacheTtl);Supports arithmetic and comparison operations.
3. clamp() Function
Built-in clamp(value, min, max) constrains a value to a range, replacing manual max($min, min($max, $value)).
clamp(150, 1, 100); // 100
clamp(-5, 1, 100); // 1
clamp(42, 1, 100); // 42
clamp(1.5, 0.0, 1.0); // 1.0
clamp('m', 'a', 'f'); // 'f' (works with any comparable type)Typical use case: clamping user pagination input.
$perPage = clamp((int)($_GET['per_page'] ?? 15), 1, 100);Throws ArgumentError if $min > $max.
4. Modifying Object Properties in Constants
Class or global constants holding objects can now have their internal properties mutated, provided the constant still references the same object instance.
final class Config { public array $items = []; }
const CONFIG = new Config();
CONFIG->items['app.name'] = 'Acme'; // Allowed in PHP 8.65. #[\Override] Attribute for Constants and Enum Cases
Extends the #[\Override] attribute (introduced for methods in 8.3, properties in 8.5) to class constants and enum cases. The compiler emits an error if the overridden constant/case does not exist in the parent.
class BaseService { public const TIMEOUT = 30; }
class CustomService extends BaseService {
#[\Override]
public const TIMEOUT = 60; // Error if BaseService removes TIMEOUT
}6. Enum __debugInfo()
Enums can implement __debugInfo() to customize output for var_dump(), dump(), or dd().
enum Status: string {
case Active = 'active';
case Banned = 'banned';
public function __debugInfo(): array {
return [
'name' => $this->name,
'value' => $this->value,
'label' => ucfirst($this->value),
];
}
}7. Precise JSON Parsing Errors
json_decode()errors (and JsonException with JSON_THROW_ON_ERROR) now report the exact line, column, and position of the syntax error.
json_decode('{"name": "Nuno", "age": }');
echo json_last_error_msg();
// Output: Syntax error near location 1:258. Stream Error Modes
Fine-grained error control for stream operations via StreamErrorMode::Error, Exception, and Silent. Adds StreamErrorCode enum and stream_last_errors() for capturing network and file I/O exceptions.
9. Native Async I/O Polling API (Io\Poll)
Built-in low-level I/O polling object wrapping epoll (Linux), kqueue (macOS), and WSAPoll (Windows). No third-party extensions required. Uses Time\Duration for timeouts. Provides a modern native event-polling foundation for PHP-FPM and async libraries like ReactPHP, Amp, and Workerman.
10. SortDirection Enum
Global built-in enum standardizing sort direction, replacing ad-hoc 'asc' / 'desc' strings or custom enums.
enum SortDirection {
case Ascending;
case Descending;
}
function orderBy(string $column, SortDirection $direction = SortDirection::Ascending): string {
return $column . ' ' . match ($direction) {
SortDirection::Ascending => 'asc',
SortDirection::Descending => 'desc',
};
}
orderBy('created_at', SortDirection::Descending); // "created_at desc"11. Native URI Builder
Complements PHP 8.5's URI parsing extension with Uri\Rfc3986\UriBuilder, enabling fluent, object-oriented construction of RFC 3986-compliant URIs (scheme, host, path, query).
12. Performance Improvements (Opcache Optimizations)
array_map() optimization : When used with first-class callables or partial functions, the compiler inlines the operation into foreach -like opcodes, avoiding closure creation.
printf() optimization : Formats containing only %s and %d are compiled directly into string interpolation.
Stateless static closure caching : Automatically caches and reuses static closures that capture no variables.
Constructor argument fast-path : Accelerates argument passing for known constructors (e.g., new self()).
13. Minor Improvements
Whitespace trimming : trim(), ltrim(), rtrim() now include form feed ( \f) in the default character mask.
array_filter() constant : New ARRAY_FILTER_USE_VALUE explicitly names the default value-filtering mode.
WeakMap reference access : Supports retrieving a reference even when the key's value does not yet exist ( $ref = &$map[$object]).
Binary packing endian modifiers : pack() and unpack() gain < (little-endian) and > (big-endian) modifiers.
Property accessibility reflection : ReflectionProperty::isReadable() and isWritable() precisely determine read/write access in the current scope, accounting for asymmetric visibility and property hooks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
