PHP has a few strict rules for variable names, and a few habits that make your code much easier to read.
The rules
- A name starts with
$. - After the
$, the first character must be a letter or an underscore. - The rest can be letters, numbers or underscores.
- No spaces and no dashes.
- Names are case-sensitive.
$totaland$Totalare different.
<?php
$name = "ok";
$_private = "ok";
$user2 = "ok";
$first_name = "ok";
echo "All valid";
All valid
These are not valid:
<?php
$2fast = 1; // cannot start with a number
$first-name = 1; // a dash is the minus sign
$my name = 1; // spaces are not allowed
Reserved words
You cannot use $this as a normal variable name. Other PHP keywords such as class or function are fine after the dollar sign ($class works), but avoid them because they confuse readers.
Naming style
PHP does not force a style, but most projects use:
| Thing | Style | Example |
|---|---|---|
| Variables | camelCase | $userName |
| Functions | camelCase | getUserName() |
| Classes | PascalCase | UserProfile |
| Constants | UPPER_SNAKE_CASE | MAX_LOGIN_ATTEMPTS |
Some older code (and WordPress) writes variables as $user_name. Both are fine. Pick one style for a project and keep it.
Choose names that explain themselves
// Hard to read
$d = 86400;
$x = "Maya";
// Easy to read
$secondsPerDay = 86400;
$customerName = "Maya";
A good name removes the need for a comment. Avoid one-letter names except for tiny loops such as $i.
Names that start with a verb are for functions
$total, $userList) and verbs for functions (calculateTotal()). It makes code read like a sentence.