Is it a good practice to load another object from within an original object, like so:
Class parent() {
$child;
function loadChild() {
$child = new Child();
$this->child = $child;
}
}
or, should the child object always be passed in separately?
Class parent() {
$child;
function setChild(child $child) {
$this->child = $child;
}
}
$parent = new Parent();
$child = new Child();
$parent->setChild($child);
Which is the better option, more flexible etc?
It depends on the situation.
The name of the second object suggests that
Child
instance will only be used by the Parent
instanceParent
instanceIf this is the case, than the first pattern (Object composition pattern) is the better one.
If the Child
instance is needed/used at other places in you code, the second pattern (Dependency injection) is more appropriate. Dependency Injection is a more flexible pattern, if you are unsure about your use case, you should generally use the Dependency Injection.