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

Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge. Glimpse streamlines Laravel development by seamlessly deploying GitHub pull requests to preview environments with the help of Laravel Forge.
Fathom Analytics | Fast, simple and privacy-focused website analytics. Fathom Analytics | Fast, simple and privacy-focused website analytics.
Shirts painstakingly handcrafted by under-caffeinated developers. Shirts painstakingly handcrafted by under-caffeinated developers.
Community Partners