Naming your Variables in PHP
Any fool can write a code that a computer can understand. Good programmers write code that humans can understand. (Martin Fowler)
Avoid meaningless variable names
Let's say we have to deal with months in an array, that's how we may probably write
$data = [‘june’, ‘july’, ‘august’];
$name = 'august';
But the above code line does not make any sense what are these we cannot identify with its name why we created this $data. Let's assume at some point we have to use this $data in our code.
in_array('august', $data);
Now the smallest piece of does not make sense what this line is doing, what kind of data is in $data, and what we are trying to find in this array. Let's make it more readable.
$months = [‘june’, ‘july’, ‘august’];
$month = 'august';
Now if we use the $months in our code anyone can understand what kind of data it has.
in_array('august', $months);
now if we look at the above line we can clearly see what we are trying to do. anyone can understand we are checking whether august exist in a list of months or not. pretty straight right?
Avoid prefixes and suffixes
In order to improve the readability and maintainability of the code, it is recommended that prefixes and postfixes be avoided in variable names in PHP. Try to use descriptive names that accurately reflect the function or substance of the variable rather than prefixes or postfixes. The following advice will help you avoid using prefixes and postfixes:
1. Use descriptive names: Pick variable names that clearly describe the information they carry or their intended use. For example, to express a counter variable, use “$counter” rather than “$iCounter”.
2. Be clear: Make sure the variable names are unambiguous and straightforward, avoiding acronyms or abbreviations that could confuse people reading your code. Use ‘$emailAddress’ as an example rather than ‘$eAdd’.
3. CamelCase or snake_case: Adhere to a naming standard that is consistent, such as camelCase or snake_case. ‘$userName’ and ‘$emailAddress’ are examples of words that begin with an uppercase letter in camelCase while succeeding words begin with a lowercase letter. All terms in snake_case are lowercase and are separated by underscores (for example, “$user_name” and “$email_address”).
4. Use nouns for variables: Variables, such as “$customerName,” “$orderTotal,” or “$productList,” should often be used to represent nouns. Don’t use verbs or verb tenses to describe variables.
5. Avoid using Hungarian notation. Hungarian notation involves prefixing variable names with their respective data types, such as “$strName” and “$intCount.” Modern PHP coding considers this practice to be archaic.