How come in PHP this works:
$myClass = 'App\MyClass';
$object = new $myClass;
But this results in an error:
$myClass = 'MyClass';
$object = new 'App\\'.$myClass;
In the second example, an unexpected T_CONSTANT_ENCAPSED_STRING
is thrown.
As it turns out, the above example is due to operator precedence since new
takes highest precedence, but...
Similarly, I can try instantiating with just a string as in:
$object = new 'App\MyClass';
And the same error is thrown. Why is this?
Instantiating an object means that we create a new object of a class in PHP. Before you can create an object, you must create a class. The class is the overall blueprint or template of the object.
To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).
The parser's implementation is not generic, therefore in some cases the parser would hiccup over things the engine could in fact handle. There (still) isn't even an official formal grammar for PHP, which makes it hard to predict things like this, without simply trying them out. It's the way of the PHP world :)
PHP expects a variable or name reference for object definitions, it simply won't allow strings. You can use this hack which is based on '' empty string named variable the is instantly created and used based on the fact that ${false}
evaluates to ${''}
as follows to create an object from string:
$obj = new ${!${''} = 'App\MyClass'}();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With