Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you instantiate a class from a string variable but not a string in PHP?

Tags:

php

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?

like image 575
samrap Avatar asked Sep 08 '15 21:09

samrap


People also ask

What does instantiate mean in PHP?

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.

How to create a new instance of a class in PHP?

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).


2 Answers

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 :)

like image 124
Gerard van Helden Avatar answered Oct 15 '22 19:10

Gerard van Helden


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'}();
like image 34
KAD Avatar answered Oct 15 '22 21:10

KAD