Variables

A variable in programming is something which can have its content changed dynamically while the program or code is running. This doesn’t always have to be the case however, a variable can become a useful marker for making simple changes to configuration settings and other sitewide details before the code is even executed.

An Analogy

Consider the scenario where have a sandwich tub - each day we go to work and we take a sandwich. The for lunch. The sandwich filling might be different each day. The constant here is that we always use the same sandwich tub.

In this example

  • The tub itself is the container (the variable declaration)
  • The sandwich is the variable.

Dynamically Typed Language

PHP is what is known as a dynamically typed language. This is different to a statically typed language in which we would have to define our datatype for each and every variable.

For example consider the code below written in C++.

string fruit = 'Banana';

Now let’s have a look at a PHP example.

$fruit = 'Banana';

In the case of PHP you can see that we don’t have a datatype defined. In the case of the C++ code sample (top sample) we don’t have a datatype set or defined. PHP doesn’t care in short, abrupt terms, the compiler takes care of this at runtime. That means we can create as many variables as we like, without a datatype set and with any type or data inserted, whether it be an integer (1), a string (“Marc”) or a float (23.99) PHP will decide what datatype to use when its compiled.

Code Sample

In this code sample I’ve created a single variable which is called $fruit I’ve then populated this variable with some data, in this case the word Banana.

$fruit = 'Banana';

In order to display this in a web browser I would need to echo it out for example…

echo $fruit;

and this would simply give me the output as below…

Banana

At the moment the $fruit variable contains the word Banana however as its a variable we can quickly change its value.

$fruit = 'Banana';

// change the value of fruit
$fruit = 'Apple';

// output the value
echo $fruit;

In this case the value of $fruit has now become Apple. It’s not particularly useful at this stage but as we get further into the module you will see how variables can become very useful.