A variable is a way of storing information, allowing it to be reused multiple times. Think of it like algebra, only a variable can be assigned a string made up of any alpha-numeric or punctuation characters. A variable is defined in the following form:
$variable_name = 'Hello World!';
Naming conventions
Note that most importantly, the variable name must be directly preceded by the dollar sign- it’s PHP’s way of identifying a variable. You should also remember that variable names are case sensitive, so $variable is not the same as $VaRiAbLe. There are also a few restrictions on what characters can be used to make up a variable name:
- must contain only alpha-numeric characters (a-z, A-Z, 0-9) and underscores (no punctuation or spaces)
- must start with a letter or an underscore (not a number)
Assigning a value
In essence the value assigned to a variable can be either textual or evaluative. So what do I mean by this? Look back at the example above- this is an example of a textual value- notice that it must be surrounded by quotes.
Evaluative values are usually in the form of maths. Look at the example below:
$var_1 = 4 + 8;
Now to me and you, this is a simple calculation, however PHP needs to be told to actually do the sum- that is, to evaluate it. We do this by not surrounding it with quotes, so the value of the variable is no longer 4 + 8, it’s 12.
If you try the first example without quotes, like so:
$var_1 = Hello World;
…you’ll just break your code because you can’t evaluate letters.
Variable value
Another form of evaluative value is another variable. Look at this:
$var_0 = 'Hello World!'; $var_1 = $var_0;
In this example we’ve assigned $var_0 the value Hello World!, and then in turn assigned it to $var_1. The result: both variables now have the value Hello World!.