Naming Conventions
In this lesson we will look at the naming conventions used in PHP.
Variables
Variables should contain only lowercase letters, use underscore separators and be reasonably named to indicate their purpose and contents. Very short, non-word variables should only be used as iterators in for() loops.
Example: Correct
Example: Incorrect
So can you guess what’s wrong with $n1, $n2, $my_name and $my_var ? One word – “Ambiguity”. Ambiguous names are the biggest reason for unreadable and ugly code. So what is “Ambiguity”? It’s simply naming a variable in a way so that you can’t guess what exactly it stores. Consider for example following snippet:
Can you guess in the above code, what is $t? No? Okay, let’s try the following code:
Can you guess now? Exactly! This is how you differentiate ambiguous variables from absolute variables. Obviously the latter approach is better because it is definitive.
Constants
Constants follow the same guidelines as do variables, except constants, should always be fully uppercase. Always use CodeIgniter constants when appropriate, i.e. SLASH, LD, RD, PATH_CACHE, etc.
Example : Incorrect
Example : Correct
TRUE, FALSE, and NULL
TRUE, FALSE, and NULL keywords should always be fully uppercase.
Example : Incorrect
Example : Correct
Functions
There are two functions majorly used:
-
lowercase with underscore separators
-
camelcase
Example
Consider the following two examples:
So which one is best – none, both are equally good!
Always keep in mind that a function should always start with a “Verb” which defines what that function is trying to do in conjunction with the name of the “Entity” being affected by this function.
Example: Incorrect
Example: Correct
Class Methods
Class names should always start with an uppercase letter. Multiple words should be separated with an underscore, and not CamelCased.
Example: Incorrect
Example: Correct
Class methods should be entirely lowercased and named to clearly indicate their function, preferably including a verb. Try to avoid overly long and verbose names. Multiple words should be separated with an underscore.