title: Dependency Injection - Is it better to pass a complete class, or the name of a class?
body: <p>For dependency injection, I understand that I have to pass an instance of one class to the main instance instead of the main class creating it's own instance, like so (php):</p>
  
  <pre><code>class Class_One {
    protected $_other;
    public function setOtherClass( An_Interface $other_class ) {
      $this-&gt;_other_class = $other_class;
    }
    public function doWhateverYouHaveToDoWithTheOtherClass() {
      $this-&gt;_other_class-&gt;doYourThing();
    }
  }
  
  interface An_Interface {
    public function doYourThing();
  }
  
  class Class_Two implements An_Interface {
      public function doYourThing() { }
  }
  
  class Class_Three implements An_Interface {
      public function doYourThing() { }
  }
  
  
  // Implementation:
  $class_one = new Class_One();
  $class_two = new Class_Two();
  $class_three = new Class_Three();
  $class_one-&gt;setOtherClass( $class_two );
  $class_one-&gt;doWhateverYouHaveToDoWithTheOtherClass();
  $class_one-&gt;setOtherClass( $class_three );
  $class_one-&gt;doWhateverYouHaveToDoWithTheOtherClass();
  </code></pre>
  
  <p>This is all fine. I know that since both Class_Two and Class_Three both implement An_Interface, they can be used interchangeably in Class_One. Class_One wouldn't know the difference between them.</p>
  
  <p>My question is, is it ever a good idea to, instead of passing an instance to setOtherClass, pass a string such as "Class_Two", and have Class_One's setOtherClass method actually create the instance itself like so:</p>
  
  <pre><code>class Class_One {
    ...
    public function setOtherClass( $other_class_name ) {
      $this-&gt;_other_class = new $other_class_name();
    }
    ...
  }
  </code></pre>
  
  <p>Does this sort of defeat the purpose of Dependency Injection, or is this completely valid? I thought this type of set up may help me with configuration, where a user can specify which class he wants to use in a string earlier on and this can later be passed to the Class_One..</p>
  
  <p>Actually, writing this out has made me think that it's probably not a good solution, but I'll still post this in case someone can give me some good feedback on why I should/shouldn't do this.</p>
  
  <p>Thanks =)</p>
  
  <p>Ryan</p>