Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the order of class definition matter in PHP?

Tags:

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?

like image 982
TaylorOtwell Avatar asked Aug 11 '10 13:08

TaylorOtwell


People also ask

Does order of functions matter in PHP?

In normal php functions, it doesn't matter. You can use both of the types. I like this answer, function definition must appear as a best practice it is like a tool that is ready to be called and you can call it later. Of course, it does not matter but for readability, function definition/declaration should go first.

How do you call a function outside the class in PHP?

Public Method/Function/Modifier/Keyword can be called outside of the class without any restriction as well as within the class access. Public Function/modifier should be accessed when the public function's programming code needed to execute the code instructions of it or else Public function will do nothing.

Which keyword is used to create an object from a class in PHP?

Definition and UsageThe new keyword is used to create an object from a class.


2 Answers

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.

like image 65
selfawaresoup Avatar answered Sep 28 '22 15:09

selfawaresoup


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.

like image 35
tplaner Avatar answered Sep 28 '22 13:09

tplaner