Martin
Martin

Reputation: 81

PHP How to create instance of class returned as string from method invocation

How to call something like this:

$instance = new ($b->method($id))();

where method(int $id): string returns class name?

The construct above gives me a syntax error, but this is ok:

$className = $b->method($id);
$instance = new $className();

I'm just wondering if and how it can be done. I was surprised that brackets could not say that content of brackets $b->method($id) should be executed first and resulting string used to object instantiating. I probably will not use it in production code, but I'm still interested.

Upvotes: 7

Views: 488

Answers (1)

Sergi Garcés
Sergi Garcés

Reputation: 26

This is not possible on PHP because 'new' needs a string or variable with a string. The () characters are used for aritmethic associations and for parameters on languaje constructions, and you can't assign to new the result of a call to another function.

Upvotes: 1

Related Questions