Cambridge IT Courses logo

Cambridge IT Courses: Specialists in advanced IT training

Cambridge IT Courses Blog: Variables in PHP

In our PHP for Beginners course we cover the basic variable syntax, the different (or not so very different) data types such as Strings and Integers and we look at examples about how variables behave within and outside functions. However, there are some more concepts related to variables which you won't come across very often but which are very useful non-the-less.


A constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script. By default a constant is case-sensitiv. By convention, constant identifiers are always uppercase. A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

Differences between constants and variables are

  • There is no need to write a dollar sign ($) before a constant, where as in Variable one has to write a dollar sign.
  • Constants cannot be defined by simple assignment, they may only be defined using the define() function.
  • Constants may be defined and accessed anywhere without regard to variable scoping rules.
  • Once the Constants have been set, may not be redefined or undefined.


// Valid constant names
define("ONE",     "first thing");
define("TWO2",    "second thing");
define("THREE_3", "third thing")
// Invalid constant names
define("2TWO",    "second thing");
define("__THREE__", "third value"); 

Local variables

A variable declared in a function is considered local; that is, it can be referenced solely in that function. Any assignment outside of that function will be considered to be an entirely different variable from the one contained in the function.

Global variables

In contrast to local variables (which are sometimes a bit limiting and force you to pass a lot of information between functions), a global variable can be accessed in any part of the program. However, in order to be modified, a global variable must be explicitly declared to be global in the function in which it is to be modified. This is accomplished, conveniently enough, by placing the keyword GLOBAL in front of the variable that should be recognized as global. Placing this keyword in front of an already existing variable tells PHP to use the variable having that name. Consider an example:

$somevar = 15;
function addit() {
GLOBAL $somevar;
print "Somevar is $somevar";

This will produce following result.

Somevar is 16

Static variables

In contrast to the variables declared as function parameters, which are destroyed on the function's exit, a static variable will not lose its value when the function exits and will still hold that value should the function be called again. You can declare a variable to be static simply by placing the keyword STATIC in front of the variable name.

function keep_track() {
   STATIC $count = 0;
   print $count;
   print "";

This will produce following result.


Variable variables

Typically when handling form data with PHP, you need to create variables one by one, plucking values out of the PHP superglobal associative array, $_POST. For each form field whose value you want to validate and store, we usually declare variables and assign values. The value we want is stored inside a named index in $_POST. Say for example we have a form with two fields: firstname, and address. We might do something like:

$firstname = $_POST['firstname'];
$address = $_POST['address'];

And we would do that for each item from the form that we need. Instead of doing that, we can use PHP's variable variables to automagically create variables. The variable names (important so we can refer to them later) will correspond to the name attributes on the form input fields. So we can do this:

foreach ($_POST as $key => $value){

The above foreach loop, while probably cryptic and not good for a person who is inheriting the code, is only three lines of code. And after we run it we will have stored all the values from the $_POST super global in variables. What are the variables named? The names of the created variables correspond to the names of the keys in $_POST, which correspond to the html name attribute of the form elements.

So in the above foreach loop, the variable $key really refers to the name of the current item in the $_POST associative array. If $key = 'firstname', then $$key really refers to $firstname! If we say $$key = "something", then we have just assigned $firstname a value of "something".

In our case, the value stored will be whatever was in the form field at the time the form was submitted. By using PHP variable variables we can automatically create variables whose names correspond to the POST data, which as you know corresponds to the name attribute on each form element.

If this concept still makes no sense, here is another attempt to explain. Normally in php, the dollar sign ($) followed by a word ($variable) denotes a variable. We can store values inside variables, e.g.

$variable = "string";

Now by using the $$ syntax, $$variable, we are referring to whatever is stored inside (single dollar sign) $variable, in this case "string". Basically, so long as $variable = "string"; assigning a value to $$variable is like implicitly declaring a new variable, whose name comes from the value stored in the first variable. So if we applied that to our example above:

$variable = "string";
// think of assigning $$variable a value as equivalent to assigning $string a value.
$$variable = 'I am stored inside $string.';            
echo $string; // outputs the string above.

Passing variables as references

Passing a variable by reference or by value to a function is a very useful concept for PHP programmers. Normally, when you are passing a variable to a functon, you are passing " 'by value' which meand the PHP procesor will make a duplicate variable to work on. When you pass a variable to a function "by reference" you passing the actual variable and all work done on that variable will be done directly on it.

function pass_by_value($param) {
push_array($param, 4, 5);

$ar = array(1,2,3);


foreach ($ar as $elem) {
print "$elem";

The code above prints 1, 2, 3. This is because the array is passed as value.

function pass_by_reference(&$param) {
push_array($param, 4, 5);

$ar = array(1,2,3);


foreach ($ar as $elem) {
print "$elem";

The code above prints 1, 2, 3, 4, 5. This is because the array is passed as reference, meaning that the function (pass_by_reference) doesn't manipulate a copy of the variable passed, but the actual variable itself.

In order to make a variable be passed by reference, it must be declared with a preceeding ampersand (&) in the function's declaration.

Object-oriented variables

When developing small and medium sized PHP projects you can probably get by with the above techniques, but once you start developing larger web applications you'll soon come to realise that it is quite difficult to keep your code organised and readable. This is when you might want to look at object-oriented programming in PHP which gives you more options of organising your code.

This is where you will come across so called access modifiers for variables (and functions): Variables can be declared as public,private or protected and this specifies from where the variable can used (e.g. from within the same class or from outside).

You'll need to learn more about object oriented concepts to understand the details, but whenever you come across public, private or protected you'll know it has something to do with object oriented programming.

Posted by Michael Gruenberger at 09:48 2010-10-26 | Trackbacks (0) | Comments (0)
Cambridge IT Courses Blog

Articles, tips and tricks discussing technical issues related to our courses

Blog Posts