I want to ask if it is good practice to make a class create instances of self or not, for example I have a class:
class MyClass {
private $data = "";
private $children = array();
public function add() {
$x = new MyClass();
// do something
// $x->some_method('');
$this->children[] = $x;
}
public function children() {
return $this->children;
}
}
That way I can use some Tree functionality, but is it alright or must I do something differently?
For example creating a parent class A, with children of class B and using a multi-dimensional array in class A to store children?
Maybe someone can suggest another method doing this?
If someone had experience with this could he please provide pros and cons he noticed.
it depends on why you’re doing it.
if you’re making the class create an instance of itself because you’re using it as a singleton, you can get into hot water with some people about the singleton design pattern in general.
on the other hand, I find the self-instantiation for the purpose of the factory design pattern to be exquisite. And I do recommend doing that for that particular case.