Using new Keyword with Expressions in PHP 8.0

Using new Keyword with Expressions in PHP 8.0

The new keyword allows creating an instance of a class. In versions prior to PHP 8.0, the new keyword can only be used with identifiers.

Let's say we have a ApiClient class.

ApiClient.php

<?php

class ApiClient
{
    public function __construct(string $token) {}
}

Then we create an instance of a class using the new keyword. All the following use cases of new keyword are valid:

main.php

<?php

require_once 'ApiClient.php';

$client1 = new ApiClient('token');  // Valid

$className = ApiClient::class;
$client2 = new $className('token'); // Valid

$prefix = 'Api';
$entity = 'Client';
$className = $prefix.$entity;
$client3 = new $className('token'); // Valid

However, in versions prior to PHP 8.0, the new keyword cannot be used with expressions. It means that the following use cases of new keyword are invalid:

main.php

<?php

require_once 'ApiClient.php';

$client1a = new 'ApiClient'('token');        // Parse error
$client1b = new ('ApiClient')('token');      // Parse error

$client2a = new ApiClient::class('token');   // Parse error
$client2b = new (ApiClient::class)('token'); // Parse error

$prefix = 'Api';
$entity = 'Client';
$client3a = new $prefix.$entity('token');    // Fatal error, it is treated as:
                                             // (new $prefix).$entity('token')
$client3b = new ($prefix.$entity)('token');  // Parse error
$client3c = new 'Api'.$entity('token');      // Parse error
$client3d = new ('Api'.$entity)('token');    // Parse error

Since PHP 8.0, the new keyword can be used with expressions using the following syntax:

new (expression)(arguments)

So, in PHP 8.0 or newer versions, all the following use cases of new keyword are valid:

main.php

<?php

require_once 'ApiClient.php';

$client1 = new ('ApiClient')('token');      // Valid

$client2 = new (ApiClient::class)('token'); // Valid

$prefix = 'Api';
$entity = 'Client';
$client3a = new ($prefix.$entity)('token'); // Valid
$client3b = new ('Api'.$entity)('token');   // Valid

Leave a Comment

Cancel reply

Your email address will not be published.