jeudi 23 juillet 2015

Is instantiating a class using `new $className()` an issue by any means? Should I use it instead of `ReflectionClass::newInstance`?

There are a few times, when dealing with something like a service container, where I have to instantiate a class, but I get the full class name from a configuration file. An example, much like the symfony container:

myService:
    class: "Vendor\Namespace\ClassName"
    arguments: [...]

Now, inside my container, I'm left with a choice: I can either instantiate this class using the following snippet, which makes use of this PHP strange feature that is evaluating the class name in runtime:

$service = new $className(...$evaluatedArguments);

Or I can instantiate it using Reflection:

$reflectionClass = new \ReflectionClass($className);
$service = $reflectionClass->newInstance($evaluatedArguments);

The latter is much more clear on what it's doing, and is, at the moment, my preferred method. However, since $className is not user input (is loaded from a .yaml file which works as an app configuration file), I can't find a reason not to use the first snippet other than readability.

It looks really sketchy, but I can't think of any technical/security reasons not to use it, and it does save some memory (I don't have to instantiate a \ReflectionClass) and is far less verbose.

My question: is using new $className an issue by any means?

Disclaimer, because I know people like to get offtopic: I'm not building a Service Container. Do not advice me to use Pimple or some other DiC instead of addressing the question, this is just an example for didatic purposes.





Aucun commentaire:

Enregistrer un commentaire