Source: stitcher.io

PHP 8.1: new in initializers

Category: PHP, PHP

Scout APM helps PHP developers pinpoint N+1 queries, memory leaks & more so you can troubleshoot fast & get back to coding faster. Let's take a look at an example; we've all written code like this: class MyStateMachine { public function __construct( private ?State $state = null, ) { $this->state ??= new InitialState(); }} In this state machine example, we'd like to construct our class in two ways: with and without an initial state.

In other words: you can use new for default arguments (which are one example of "initializers"): class MyStateMachine { public function __construct( private State $state = new InitialState(), ) { }}

Here's what the transpiled version looks like: class MyStateMachine { private State $state; public function __construct( State $state = new InitialState(), ) { $this->state = $state; }} #limited-input Limited input
Newsletter

Get the latest Laravel/PHP jobs, events and curated articles straight to your inbox, once a week

Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future. Achieve superior email deliverability with ToastMail! Our AI-driven tool warms up inboxes, monitors reputation, and ensures emails reach their intended destination. Sign up today for a spam-free future.
Community Partners