PHP 8.1 made me delete these 30 lines of code

The less code you write, the less you have to maintain

Read-only properties

One of the most useful features of PHP 8.1 is protecting the write of a property. Before, when you made a property “public”, anyone could just swap it, even accidentally, and break a class.

// This is allowed
$handler->user->name = 'John Doe';
// This is NOT allowed
$handler->user = new User;

Initializing with “new"

Optional arguments just got slightly buffed. The most common pattern is to add default values as strings, integers, floats, or null, and just then initialize it in the class constructor. This is very common, no sin committed.

// This is allowed
public function __construct(
public User $user = new User('John')
)
// This is NOT allowed
public function __construct(
public User $user = User::make('John')
}

Graphic Designer graduate. Full Stack Web Developer. Retired Tech & Gaming Editor.