debuggable

 
Contact Us
 

Naming Conventions

Posted on 16/3/07 by Tim Koschützki

Naming conventions are one of the easiest, but most powerful tools to make your code readable and easy-to-follow. Over the years, certain standards have developed for most programming languages, including PHP. Let's outline them here.

Naming Variables

  • Use all camel-case; start new words with a capital letter. Example: $thisIsAvariable.
  • Use descriptive names (except loop variables).
  • Loop variables can be of the usual variety: $i, $j, $k, etc.
  • Count variables should follow the format $*_count, e.g. $bug_count
  • Global variables should be prefixed with g_
  • Temporary variables should be prefixed with t_
  • $query and $result should be used for SQL query and results respectively

Some people suggest, that one should prefix variables depending on where they are coming from and whether they have been "cleaned" yet (as in slashes stripped, etc.). I liked the idea at first, but admittedly, as your scripts grow, the code becomes more and more unreadable if you deal with variables like $c_resultSet and $i_loopVar for a cleaned resultset and an integer.

If you code in a clean way, that is with many small functions, you should be good to go without prefixing.

Naming Functions

  • Use all camel-case again. Example: function thisIsMyFunction()
  • Keep functions to 5 words or less
  • Name the function after what it does. Something like functionA() doesn't help. cleanSqlQuery() is much better.

Naming Classes

  • Use all camel-case again with the first letter being capitalized. Examples: class MyDog(), class RequestParser(), class BbCodeParser()
  • Keep classes to 5 words or less
  • Name the class after what it does. Something like class SomeClass is not descriptive enough. Class SqlQuery is much better.

Naming Class Methods

  • Use the same strategy as for normal functions. Do not start with a capital letter as indicated in some guides. Justification: When using typehinting, this can get quite confusing. Example: $requestParser = RequestParser $this->CreateRequestParser();
  • Keep methods to five words or less
  • Name the method after what it does.

 
&nsbp;

You can skip to the end and add a comment.

This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.