tags:

views:

79

answers:

5

If I have several classes in different php files that I'm including into a single file, and some of these classes have dependencies on other classes, does the order in which they are included matter? Or, is simply including them (in any order) before they are used all that matters?

A: 

Simply include them before they needed and everything will be fine.

fabrik
+9  A: 

Yes, it matters.

I recommend to use autoloading to resolve class dependecies. That way classes are only laoded when they are actually needed and you don't have to bother with including every single PHP file by hand.

You have to keep every class in it's own file for this to work, though. But that's a good way to keep everything tidy and clean, anyway.

Techpriester
So, are you saying that even if I include every file and dependency I need before using them, there can still be problems because of the order in which I include them?
TaylorOtwell
Yes, and keeping track of all your includes is pretty annoying. Autoloading can also improve your performance since it only loads what your script actually needs. Loading PHP files is usually an I/O-operation, which is mostly horribly slow.
Techpriester
A: 

It would matter as if one class tried to use another which had not yet been parsed, then an error would occur. The best option is to place the classes in the script so the dependancy will still be intact.

Liam Spencer
A: 

If they all are in the same file, no the order shouldn't matter. There are some rare instances (I've seen with namespaces) where the order does matter, but don't worry about that too much unless you're pushing the envelope.

Try it. The worst that can happen is that it'll give you an error...

ircmaxell
+3  A: 

Within 1 PHP file, you can declare functions/classes anywhere and call them anywhere (within that file), order does not matter.

As for includes, you must include the file BEFORE you attempt to use a declared function/class within that file.

evolve
keeping everything in one file may seem comfortable for small projects but it prohibits you from reusing parts of the software and you have to load the entire stuff all the time, even if you don't actually use all of the classes/functions. It's quite a big waste of performance.
Techpriester