7

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.

9
  • 4
    Possible duplicate of How to instantiate from a string class name in PHP? You probably should not use the crazy code provided there... Commented Jan 22, 2018 at 13:58
  • I don't think it's a duplicate. And at least it's better worded and shows more research on the issue. Commented Jan 22, 2018 at 14:07
  • What's wrong with doing the ok version? First version is quite unreadable. Commented Jan 22, 2018 at 14:09
  • 2
    I think you need to clarify this question: Why is it so important that you don't store the class name in a variable? That's probably the cleanest solution. If you wanted, you could write a function that takes the class name as parameter and calls new on it, but that would be much uglier still. Commented Jan 22, 2018 at 14:09
  • 1
    This simply hasn't been implemented by the AST lexer. It currently only supports simple variables. This shouldn't be too difficult to implement if you put in a feature request: github.com/php-src/php/blob/… Commented Jan 22, 2018 at 17:46

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.