This tutorial explains how to define and use constants in PHP. Constants contain a fixed value that cannot be changed after it has been set. Constants are useful for when you want to store data that you need to protect from accidentally being altered.
Constant names follow the same rules as variable names except they don’t start with a $ dollar sign. However, constant names are usually capitalised to distinguish them from variable names. Constants must also be defined using the define() function. Constants can contain alphanumeric values (like strings, integers, and floating point numbers) but can’t store Boolean values or represent a NULL value of an object.
Constants cannot be included in mixed strings when being displayed and must be concatenated instead. Watch the video below to find out how to define and use constants and then scroll down to see the sample code.
Sample PHP code:
echo 'Hello ' . USERNAME;
You can watch the video all about variables and data types here.
var myVariable = 50;
// Variable names (identifiers) have to begin with lower or uppercase letters or an underscore
// Variable names cannot begin with a number, however they can contain a number
// To declare a variable, use the keyword var
// You can assign a value to a variable when you declare it, in one line (as above)
// ...or you can declare a variable and then assign a value later, as below...
myVariable2 = "Hello there";
// This displays the value of myVariable in the browser window
If you have created your own variables and assigned them each a value (such as a string or integer), then you will already be familiar with the assignment operator which is a single = (equals sign).
You can view the video below to see how to use these operators and scroll down to see the sample code.
The code below shows how you can use a range of operators when working variable assignments and calculations.
var x = 5, y = 10; //variables can be initialised on one line, separated by commas
var z = x + y; // this is how variables can be added
z++ //this increases the z variable value by 1
z-- //this decreases the z variable value by 1
// operators include + (plus) - (minus) * (multiply) / (divide) and % (modulus) which returns the remainder from division
x+=y; //this is an example of compound addition. It is the equivalent of x = x + y
// variables can be added using the compound addition += , compound subtraction -= , compound multiplication *= or compound addition /=
document.write(z); // now let's see what the z variable displays after these modifications.
Next tutorial: Strings