Alex Rivera | Logout

Implications of Instantiating Objects with Dynamic Variables in PHP

Asked 2008-09-07T01:27:50.883
12

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

  1. You lose the ability to pass arguments into a constructor (LIES. Thanks Jeremy)
  2. 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?

Edit
Report

3 Answers

5

I would add that you can also instanciate it with a dynamic number of parameters using :

<?php

$class = "Test";
$args = array('a', 'b');
$ref = new ReflectionClass($class);
$instance = $ref->newInstanceArgs($args);

?>

But of course you add some more overhead by doing this.

About the security issue I don't think it matters much, at least it's nothing compared to eval(). In the worst case the wrong class gets instanciated, of course this is a potential security breach but much harder to exploit, and it's easy to filter using an array of allowed classes, if you really need user input to define the class name.

answered 2008-09-15T12:26:37.537
4

There may indeed be a performance hit for having to resolve the name of the variable before looking up the class definition. But, without declaring classes dynamically you have no real way to do "dyanmic" or "meta" programming. You would not be able to write code generation programs or anything like a domain-specific language construct.

We use this convention all over the place in some of the core classes of our internal framework to make the URL to controller mappings work. I have also seen it in many commercial open source applications (I'll try and dig for an example and post it). Anyway, the point of my answer is that it seems well worth what is probably a slight performance decrease if it makes more flexible, dynamic code.

The other trade-off that I should mention, though, is that performance aside, it does make the code slightly less obvious and readable unless you are very careful with your variable names. Most code is written once, and re-read and modified many times, so readability is important.

answered 2008-09-07T02:55:38.223
0

@coldFlame: IIRC you can use call_user_func(array($className, 'someStaticMethod') and call_user_func_array() to pass params

answered 2008-09-15T14:32:35.360

Your Answer