An object method that instantiates a class

I want to ask if creating a class that creates instances of self is good practice 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 of the Tree functions, but is everything ok or should I do something differently?

For example, creating a parent class A , with children of class B, and using a multidimensional array in class A to store children

Can anyone suggest another way to do this?

If someone had experience with this, he could provide all the pros and cons that he noticed.

+4
source share
3 answers

Is it good practice to create a class to instantiate self?

it depends on why you are doing this.

if you create an instance of a class because you use it as a singleton, you can get into hot water with some people around the singleton design pattern as a whole.

on the other hand, I believe that self-creation for the purpose of designing a factory template is elegant. And I recommend doing this in this particular case.

+4
source

In general, I would not do that. The only time I could make sure it would be suitable would be if you used it in a singleton, which seems to be wrong.

Here 's an article on constructor best practices. This is pretty intense, but full of information!

+1
source

I don’t think this is a tough and quick rule anyway. It depends on the problem space you are trying to solve.

That is, if you create a structure, such as a tree, and this structure contains nodes that are of type Tree, then it can be quite reasonable for trees to create instances of itself depending on the requirements of the tree in the subject application.

You also see something roughly similar to your example in the Singleton design pattern, where you want to create exactly one universal object instance.

So, I think the answer lies in the suitability of the solution to the problem. Hope this makes sense.

+1
source

All Articles