PHP 8.1 is Here
Published on by Paul Redmond
The PHP team announced the release of PHP 8.1 yesterday:
🥳 PHP 8.1 is released!
— php.net (@official_php) November 25, 2021
🔗 Read all about it at: https://t.co/ToeHc3YGau
♻️ Migration Guide: https://t.co/BVVZ7lSXd1
🐘 Many thanks to the contributors for everything they implemented, and the RMs to get this amazing new version released!
❓ What's your favourite new feature?
According to the announcement, here is a list of the main features for PHP 8.1:
- Enumerations
- Readonly properties
- Fibers
- Pure Intersection Types
- never return type
- First-class Callable Syntax
- "final" modifier for class constants
- New fsync and fdatasync functions
- New array_is_list function
- Explicit Octal numeral notation
- And much much more...
Enumerations
PHP 8.1 supports Enumerations (Enums) natively, providing a rich api for defining and working with Enums:
enum Status{ case Draft; case Published; case Archived;}function acceptStatus(Status $status) {...}
Read-only Properties
Read-only properties cannot be changed after they are initialized. You can be confident that your data classes are consistent. PHP 8.1 can reduce boilerplate by defining public properties the author does not intend to change, instead of private properties accessible via "getter" methods:
class BlogData{ public readonly Status $status; public function __construct(Status $status) { $this->status = $status; }}
Intersection Types
You can use intersection types when needing to satisfy multiple constraints at the same time:
function count_and_iterate(Iterator&Countable $value) { foreach ($value as $val) { echo $val; } count($value);}
First-class Callable Syntax
You can make make a closure from a callable by calling it and passing ...
:
function add(int $a, int $b) { // ...} $add = add(...);$add(1, 5);$add(5, 3);
And much more...
To get up to speed on these new features, check out the PHP 8.1.0 Release Announcement page for examples before/after PHP 8.1, as well as performance improvements.