Always use meaningful variable and function names in PHP

Think About the following code $a=”I Am John Doe”;

$b=explode(“ “,$a);

echo “Total Number of words in $a is “.count($b);

Now how about this, $name=”I Am John Doe”;

$num_of_words=explode(“ “,$a);

echo “Total Number of words in $name is “.count($num_of_words); Well, the example was too simple. But things can go terribly wrong when not using meaningful variable names in PHP or any other language’s codes. Even you’ll forget at some point of time what was the variable $a for and $b. And it really pisses other developers when using some one’s code which didn’t follow good naming convention. And when i see codes in those messy fashion it makes me angry like the Goku below.
Angry Goku

And the end result is inefficiency and waste of valuable time. There are various naming conventions practiced for coding. PHP has it’s own style where underscore is massively used. And it’s quite comfortable to use. $last_name is more readable than $lastname. So variables/functions can be made quite meaningful when they are written. To cut the story short, here’s some suggestions from me: 

  • Always use lower case in functions and variables unless specifically asked by Frameworks. Like function Login()

    function login()
  • Functions/Variable separators should be with underscores. e.g function get_users()..

    function getUsers() // It’s better to avoid Camelize
  • Function names should be grammatically sensible. For example if we want a function that returns all the countries of the world, we should name it like function get_all_countries().

    function get_all_country().. // wrong plural

    function get_country_all().. // Hard to make sense what this means
  • Be consistent with one practice throughout the whole project so that other people can confortably assume the convention.
  • If possible keep signature of datatypes or return types in variable function name. Like if we want to store users as an array in a variable it should be $user_array instead of $users
  • Using imperatives. Meaning put some verbs in functions to know what the function is doing. Instead of function notes(), try to write function get_notes(); which is kind of self explaining.
  • Avoid homophones: e.g., foo, fu, phoo, etc.
  • Avoid generic names such as tmp, buf, reg.
  • Avoid intentionally misspelled words such as lo or lite.

Well, there can be many more suggestions for better coding, because "coding is poetry" for programmers.

 

Author's gravatar

Md. Mahbubur Rahman

Your email address will not be published. Required fields are marked *