Variables
Variables in PHP—that is, things that store data—begin with $ followed by a letter or an underscore, then any combination of letters, numbers, and the underscore character. This means you may not start a variable with a number. One notable exception to the general naming scheme for variables
are "variable variables," which are covered in the next chapter. A list of valid and invalid variable names is shown in Table 4-1.
Table 4-1. Valid and invalid variable names
|
|
Correct |
|
|
Correct |
|
|
Correct |
|
|
Correct |
|
|
Incorrect ; starts with a number |
|
|
Incorrect ; starts with a number |
|
|
Correct; numbers are fine at the end and after the first character |
|
|
Correct |
|
|
Incorrect; no symbols other than "_" are allowed, so apostrophes are bad |
Variables are case-sensitive, which means that $Foo is not the same variable as $foo, $FOO, or $fOO.
Assigning variables is as simple as using the assignment operator (=) on a variable, followed by the value you want to assign. Here is a basic script showing assigning and outputting data—note the semicolons used to end each statement:
<?php
$name = "Paul";
print "Your name is $name\n";
$name2 = $name;
$age = 20;
print "Your name is $name2, and your age is $age\n";
print 'Goodbye, $name!\n';
?>There we set the $name variable to be the string Paul, and PHP lets us print out that variable after Your name is. Therefore, the output of the first print statement is Your name ...