PHP 8.1 will be released within a few months, and once again, many peculiarities of PHP 8.1 get me excited! So in this post, I want to share the actual impact of PHP 8.1 on our code that I’ve observed.
Enums
A much-anticipated feature, enums are coming in PHP 8.1. Earlier, we’ve utilized spatie/enum or myclabs/php-enum for enum support, But now PHP 8.1 will come with this exciting feature. In PHP 8.1 we’ll convert this code:
/**
* @method static self draft()
* @method static self published()
* @method static self archived()
*/
class StatusEnum extends Enum
{
}
To this
enum Status {
case draft;
case published;
case archived;
}
Array unpacking with string keys
This one might look like a little one, but it has annoyed me more than once: Before PHP 8.1 only list arrays could be unpacked. Here’s an example:
$a = [1, 2, 3];
$b = [4, 5, 6];
// This is allowed
$test = [...$a, ...$b];
While arrays with string keys cannot:
$a = ['a' => 1, 'b' => 2, 'c' => 3];
$b = ['d' => 4, 'e' => 5, 'f' => 6];
$test = [...$a, ...$b];
// You'd need to use array_merge in this case
$test = array_merge($a, $b);
And so, one of the great features of PHP 8.1 that will make my life easier, is that arrays with string keys can now be unpacked as well!
$a = ['a' => 1, 'b' => 2, 'c' => 3];
$b = ['d' => 4, 'e' => 5, 'f' => 6];
// :)
$test = [...$a, ...$b];
Class properties: initializers and read-only
Another remarkable feature of PHP 8.1 is that now we can set default arguments in function parameters. Once again, this feature is such a quality-of-life improvement. Imagine you’d want to set a default state class for a BlogData object. Before PHP 8.1 you’d have to make it nullable and set it in the constructor:
class BlogData
{
public function __construct(
public string $title,
public ?BlogState $state = null,
) {
$this->state ??= new Draft();
}
}
PHP 8.1 provides that new call directly in the function definition. It will be immense:
class BlogData
{
public function __construct(
public string $title,
public BlogState $state = new Draft(),
) {
}
}
Class properties can be marked as readonly, meaning they can only be written once.
class BlogData
{
public function __construct(
public readonly string $title,
public readonly BlogState $state = new Draft(),
) {
}
}
First-class callable syntax
As if that wasn’t adequate, there’s now also the first-class callable syntax, which provides you a neat way of constructing closures from callables.
Before you’d had to write something like this:
$strlen = Closure::fromCallable('strlen');
$callback = Closure::fromCallable([$object, 'method']);
In PHP 8.1, you can do… this:
$strlen = strlen(...);
$callback = $object->method(...);
There are even more features in PHP 8.1, but these are the ones I’m most passionate about.