Does the order of class definition matter in PHP?

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.


Yes, it matters. This is mentioned as a note in object inheritance documentation:

Unless autoloading is used, then classes must be defined before they are used. If a class extends another, then the parent class must be declared before the child class structure. This rule applies to classes that inherit other classes and interfaces.

I recommend to use autoloading to resolve class dependencies. That way classes are only loaded 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.

Tags:

Php