Using new Keyword in Initializers in PHP 8.1

Using new Keyword in Initializers in PHP 8.1

The new keyword allows creating an instance of a class. Since PHP 8.1, the new keyword can be used in initializers (e.g. parameter default values, attribute arguments, etc.).

In versions prior to PHP 8.0, we can write the following code to initialize the default instance of the class in constructor:

LoggerInterface.php

interface LoggerInterface {}

NullLogger.php

class NullLogger implements LoggerInterface {}

ApiClient.php

<?php

class ApiClient
{
    private LoggerInterface $logger;

    public function __construct(?LoggerInterface $logger = null)
    {
        $this->logger = $logger ?? new NullLogger();
    }
}

Since PHP 8.1, the new keyword can be used inside parameter default values. We can rewrite previous code as follows:

ApiClient.php

<?php

class ApiClient
{
    private LoggerInterface $logger;

    public function __construct(LoggerInterface $logger = new NullLogger())
    {
    }
}

We can use new keyword with promoted properties as well:

ApiClient.php

<?php

class ApiClient
{
    public function __construct(private LoggerInterface $logger = new NullLogger())
    {
    }
}

The new keyword cannot be used to create an instance of a class as default value for properties.

ApiClient.php

<?php

class ApiClient
{
    private LoggerInterface $logger = new NullLogger(); // Error
}

Leave a Comment

Cancel reply

Your email address will not be published.