Backend Development

Using new in Initializers in PHP 8.1

Using new in Initializers in PHP 8

PHP 8.1 introduced a powerful and convenient feature: using new in initializers. This change enhances readability and maintainability of class properties and default parameter values by allowing the direct use of new expressions where only constant values were previously allowed.

 

 

 

The Problem Before PHP 8.1

Prior to PHP 8.1, you could not assign a newly instantiated object directly as a default value for a class property or parameter. You had to do this inside a constructor or method body:

class Logger {
    public function __construct(public string $channel = 'default') {}
}

class Service {
    public Logger $logger;

    public function __construct() {
        $this->logger = new Logger();
    }
}

This made the code unnecessarily verbose, especially when dealing with immutable or default value objects.

✅ The PHP 8.1 Solution: new in Initializers

With PHP 8.1, you can now directly assign objects using new in property declarations and function/method parameter defaults:

class Logger {
    public function __construct(public string $channel = 'default') {}
}

class Service {
    public Logger $logger = new Logger(); // 👈 This is now allowed in PHP 8.1
}

Or for function arguments:

function handleRequest(Logger $logger = new Logger()) {
    // $logger is guaranteed to be a Logger instance
}

This makes your code more concise and improves readability.

 

Example 1: Property Initialization

class Config {
    public array $settings = [];
}

class App {
    public Config $config = new Config(); // Direct initialization
}

Example 2: Default Parameter Object

class Options {
    public function __construct(public bool $verbose = false) {}
}

function run(Options $options = new Options()) {
    if ($options->verbose) {
        echo "Running in verbose mode...";
    }
}

 

 

Things to Keep in Mind

  • Only objects created with new are allowed. You still can’t use function calls or other expressions as default values.

  • This feature is especially useful with readonly properties and value objects, which are commonly instantiated with default or constant-like behavior.

  • This is a compile-time improvement: instantiations are still evaluated at runtime, so if a class has side effects in its constructor, they will still happen when the object is created.

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
0
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments