Visit the Official PHP Website
Search this Site

PHP Programming

By James N Hitz

Variables

A variable is a smart, little hypocrite whose value changes depending on the prevailing circumstances. In it's true status, a variable is simply a named memory location. It therefore has:

  1. a name
  2. a value
  3. a scope
  4. a data type

Think of variables like a set of boxes where each box is labelled. You can put something in the box. In this case, the label is the name of the box and the value is whatever you decide to put inside the box.

When it comes to the case of PHP and computers, these little "boxes" are simply "partitions" in the computer's memory (RAM).

We will for now ignore the two later issues - scope and data type, and concentrate on name and value. Starting of course with variable names.

Defining A Variable Name

A variable name in PHP has a few characteristics:

  1. It must start with a dollar sign ($)
  2. The first character after the dollar sign ($) MUST be alphabetic (a-z A-Z) or an underscore (_) {ACII characters 127 through 255 are also valid}
  3. All the other characters in the variable name must only be made of aphabetics, numbers or the underscore
  4. A PHP variable is case sensitive i.e PHP, Php and php are all considered to be different because of the difference in the capitalization.
  5. A PHP variable MUST NOT contain a space (or spaces).

Examples of valid PHP variables are:

$name, $_inString, $énglish

Hey! No spaces allowed?!

Yeah! No Spaces allowed. If you have long variables, you can capitalize the Initial Capitals (like $aVeryLongVariable; ), or use underscores to separate the names in the variable (like $a_very_long_variable;).

Although it is allowed to use short, cryptic variable names (like $x; for example), always avoid them because they make your code very hard to maintain and debug especially if you look at your code several months later. Don't make the variables too long either. This makes typing them an error-prone affair, and you still have to do a lot of typing too (and as it is, I am very lazy dude).

<< Introduction to Lesson | Types of Variables >>