I was thinking about single responsibility principle, and I came up with this question. Let's say a class needs to be injected by another. Is it better to send second class into the first one's constructor as parameter, or just include it in the first one's constructor?
To explain my question I wrote this little code. In the first code, A requires B and creates an object of B in its constructor.
require_once('classb.php');
class A {
protected $b;
public function __construct(){
$this->b = new B;
}
}
In the second code, A takes B as a parameter and assigns it to internal variable $b in the constructor.
class A {
protected $b;
public function __construct(B $b){
$this->b = $b;
}
}
I know that one benefit of using second way, if A needs to get C also in some cases; instead of sending class itself to A's constructor an interface will act like reference of the class that is needed to be done.
On the other hand, if we are sure that there will be only one class coming inside A, using first one saves us time and lines to initialize B every single time.
The question is that if doing like the first way disturbs any best practice principles or has some down sides?