
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:
Â
Example 1: Property Initialization
class Config { public array $settings = []; } class App { public Config $config = new Config(); // Direct initialization }