Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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.

like image 268
Martin Avatar asked Jan 22 '18 13:01

Martin


1 Answers

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.

like image 160
Sergi Garcés Avatar answered Sep 28 '22 05:09

Sergi Garcés