Should I pass an object into a constructor, or instantiate in class?

Posted by Prisoner on Programmers See other posts from Programmers or by Prisoner
Published on 2012-01-18T15:37:45Z Indexed on 2012/08/29 9:49 UTC
Read the original article Hit count: 160

Consider these two examples:

Passing an object to a constructor

class ExampleA
{
  private $config;
  public function __construct($config)
  {
     $this->config = $config;
  }
}
$config = new Config;
$exampleA = new ExampleA($config);

Instantiating a class

class ExampleB
{
  private $config;
  public function __construct()
  {
     $this->config = new Config;
  }
}
$exampleA = new ExampleA();

Which is the correct way to handle adding an object as a property? When should I use one over the other? Does unit testing affect what I should use?

© Programmers or respective owner

Related posts about object-oriented

Related posts about unit-testing