Syntax for object creation specification?

PHP uses keyword new to create an instance of given class. The description in PHP manual seems rather vague, find it unclear what syntax is allowed here. Which tokens/expressions can be passed to new.

class Foo {}

// using class identifier obviously works
new Foo();  // => Foo{#2574}
// ... including omitting parens for constructor arguments as optional 
new Foo;    // => Foo{#2577}

// passing class name in a string (mentioned in manual) however fails
new "Foo";
new "Foo()";
new "Foo"();
// => PHP Parse error: Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

// passing class name in a string works only indirectly, through a variable (why?)
$className = "Foo";
new $className;    // Foo {#2580}

// other expressions resulting in *string* value also does not seem to work
function getFoo() {return "Foo";}
new (getFoo());
// => PHP Error:  syntax error, unexpected '(', expecting ';'

What all possible syntax for new is allowed? Is there some syntax reference for PHP, where this and other core language constructs are described in detail? Like The Python Language Reference?

1 answer

  • answered 2021-04-21 13:05 Zoli Szabó

    The PHP manual says:

    If a string containing the name of a class is used with new, a new instance of that class will be created.

    It can indeed be interpreted in a wrong way (i.e. using string constants: new "Foo"), but one can quickly realize you would never do that. If you specify a constant string value, you can also write it in the conventional form (new Foo), so there would be no advantage there.

    However, there's an advantage of being able to use variables holding string values, e.g. $className = "Foo"; new $className;, because it makes it possible to dynamically create class names and instantiate them. Nobody should abuse this possibility, but it can come in handy in some situations.