What are the performance, security, or ‘other’ implications of using the following form to declare a new class instance in PHP
<?php $class_name = 'SomeClassName'; $object = new $class_name; ?>
This is a contrived example, but I’ve seen this form used in Factories (OOP) to avoid having a big if/switch statement.
Problems that come immediately to mind are
You lose the ability to pass arguments into a constructor(LIES. Thanks Jeremy)- Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?)
What other implications are there, or what search engine terms other than ‘Rank PHP Hackery’ can someone use to research this?
One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff.
As long as you don’t do something like
you are probably fine 🙂
(my point being: Dynamically looking up a class here and then doesn’t hurt. If you do it often, it will).
Also, be sure that $classname can never be set from the outside – you’d want to have some control over what exact class you will be instantiating.