Object-oriented – Multiple instance of the same class

class-designdatabaseobject-orientedobject-oriented-designPHP

I have a class named "Category" to handle all the operations and data about my categories. Now, my class is created however I need to find a way to build an object for each of the categories in my database.

In a PHP OOP structure, how should I do this? I was thinking about maybe making some kind of CategoryCollection class which only purpose would be to create an array containing a Category object for each of my categories, however I am not quite sure this would be the best way to achieve this.

Best Answer

You can always create multiple instances of a class! This is what classes are designed for! Each object will hold its own individual inner variables (unless they are static, in which case they are shared).

If you wish to store them all into a variable, you can use any collection type (List, Collection, Array). PHP offers its own array type

If you wish to pass a list of categories to a function, or return a list of categories. Fill the array with objects and pass it along.

Related Topic