Question

A quick question about best practice with PHP classes. I have seen people use filenames such as something.class.php to organise their classes in external files.

So, is it best practice to have one file per class, or multiple classes per file.

At the moment, I am scripting an RPG and have a single class_lib.php file. I currently have just character-related classes in there, and before I go any further would like to know if it's more suitable to keep classes grouped in files, have all classes in a single file, or keep each class to its own file.

What are the advantages/disadvantages of each approach?

Made this CW as it may not have a definite answer

Was it helpful?

Solution

Their are pros and cons of both approaches. Separating classes into separate files allows you to instantly know which file to modify if you need to update a class and keeps all logic related to that class in the same place. It is also beneficial from a source code repository standpoint to separate files. It increases the amount of load to include a ton of files, however this is most likely negligible. Another disadvantage is having to open numerous files to in the course of coding and it can be a pain to navigate if you decide to use folders in the structure as well.

Having related classes in the same file is more convenient than anything and can be confusing to figure out which file holds the class you need to modify.

If your project won't be terribly large it will most likely be up to you on how you want to organize it. But think about it in terms of "If I don't touch the code in 6 months, will I remember where to go to edit this class?"

OTHER TIPS

One file per class, with autoload to include them only when they're needed

Keeping classes in separate files allows for autoloading. Conceivably, it might help with performance if some classes--which you would otherwise put in one big file--are used rarely (N.B., this is just blind speculation. Autoloading itself might incur an offsetting performance cost.)

It depends on taste, and the sizes of your classes. The separation is purely for organization. So, if you think it would be easier in one file, or one class per file, depends on you.

Advantages: easier to find what you want. Less scrolling!

Disadvantages: constant switching between files. May be annoying when making new classes on the fly.

One class, one file. IMO, it's easier from an organizational point of view.

Other tips:

  • Keep levels of inheritance and parameters list to an absolute minimum. Any more than 5 or 6 becomes a bit too complex
  • Use the most restrictive scope qualifiers
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top