I answered a question (link) that I used a creation of the new object in another class' constructor, here the example:
class Person {
public $mother_language;
function __construct(){ // just to initialize $mother_language
$this->mother_language = new Language('English');
}
And I got the comment from user "Matija" (his profile) and he wrote: You should never instantiate a new object inside object consturctor, dependencies should be pushed from outside, so anyone who uses this class knows what is this class dependent on!
Generally, I can agree with this, and I understand his point of view.
However, I used to do this this way very often, for example:
- as the private properties other classes give me functionality that I can solve not duplicating the code, for example I can create a list (class implementing
ArrayAccess
interface) of objects), and this class would be used in another class, that has such a list of objects,
- some classes use for example
DateTime
objects,
- if I
include
(or autoload) dependant class, one should have no problem with errors,
because dependant objects can be very large number, passing all of them to the class constructor can be very long and not clear, example
$color = new TColor('red'); // do we really need these lines?
$vin_number = new TVinNumber('xxx');
$production_date = new TDate(...);
...
$my_car = new TCar($color, $vin_number, $production_date, ...............);
as I was "born" in Pascal, then in Delphi, I have some habits from there. And in Delphi (and FreePascal as its competitor) this practice is very often. For example, there is a TStrings
class that handles array of strings, and to store them it does not use array
s but another class, TList
, that provides some useful methods, while TStrings
is only some kind of interface. The TList
object is private declared and has no access from outside but the getters and setters of the TStrings
.
- (not important, but some reason) usually I am the one who uses my classes.
Please explain me, is it really important to avoid creating objects in constructors?
I've read this discussion but have still unclear mind.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…