Like any other scripting language, PHP can manipulate variables: tokens that store values that can be altered or changed. There are a few points to note regarding PHP variables in particular:
- In PHP a variable is created by having a
$sign in front of the variable name; for example:
- The variable name must follow the standard naming convention we have kept to thus far. i.e. alphanumerics only, no spaces or other odd characters. A variable may start with an underscore (
$_foo) but not a number. You cannot use the term
$thisas a variable, as it is reserved.
- Variables are case sensitive.
$foois a different variable from
$Foo. It is traditional to start a variable name as lowercase, and to capitalise any words appended to the name (aka camelCase). For example:
$customerFirstName. camelCase is optional; the important thing is to be consistent in whatever naming convention you decide to use.
- Variables in PHP are not typed or scoped: that is, by default they are not explicitly set for handling numbers, characters, or any type of data in particular. A variable can change from holding a number to a letter to an array at any time.
- Variables take the last value they are set to. That is, you cannot make a variable that cannot have its value changed. (That, by definition, would be a constant). Remember that PHP scripts are executed “top down” just as HTML is, in the order that it is written. A typical error by developers beginning with work with PHP is testing a variable via an
ifstatement before setting it to a value.
- Variables can be created “on the fly” at any point inside a PHP script, and by association anywhere on a web page; they do not have to be declared.
- User-created variables are not global by default. That is, variables are not passed automatically between the pages of a website.
- Variables can be concatenated.
- Variables may contain arrays, strings, and other variables. Variables are not interdependent; that is, setting
$x = $yand later changing the value of
$ywill not automatically change the value of
Some variables are predefined. These can usually be identified by the fact that they are always written in uppercase; for example