Should I pass an object into a constructor, or instantiate in class?
- by Prisoner
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?