An introduction to variables
PHP is like any other programming language in that it has variables. Variables are used to store information on a temporary basis whilst a program is running. This tutorial will show how variables work in PHP.
Variables are ways of storing information temporarily on memory, paritcularly the server based memory.
Variables always start with the $ sign and do not need to be declared with a type. This is because PHP is a loosely typed language.
<?php $test = 51; $test = $test + 3; //This should output The answer is 54 echo 'The answer is '; echo $test; ?>
With PHP there is no need to instantiate variables before using them.
PHP has something called a session. The concept of a session is when the client is still on that website, the session is still open. Session variables can then be stored so that preferrences or baskets/orders are stored for each user. How this works is that a server keeps a small file, uniquely identifying the machines or users that are using the page and stores information in it.
<?php $test = 51; session_start(); $_SESSION['myTest'] = $test; ?>
The example above declares a session variable with the name 'myTest'
with the value of
We can then retrieve the value of myTest by calling a session variable again as such:
<?php session_start(); $test = $_SESSION['myTest']; echo $test; ?>
Note, it is very important to start a session before calling a session variable.
In PHP cookies are stored and retrieved as such:
<?php setcookie('myTest', 'value'); $test = $_COOKIE['myTest']; echo $test; ?>
PHP also allows the use of constants.
Constant vs variables
There is a major difference between a constant and a variable. The most crucial part is that a constant cannot be changed, it's value is constantly the same.
A variable can vary. This means the value can change at any time and does not have to defined at the start.
Below is how it is defined in PHP:
<?php define ('MYTEST', 'value'); $test = MYTEST; echo $test; ?>
The example above is case-insensitive. This means we can also
refer to MYTEST using the name mytest. To make it case sensitive
a third parameter is passed with the value
<?php define ('MYTEST', 'value', true); $test = Mytest; echo $test; ?>
The true at the end of the
us that the constant is case-sensitive.