Tuesday, 4 May 2010

Variables and Constants

In this screencast we will compare constants and variables, then use them to calculate the perimeter of a circle.

Constants and variables are both store data and can be used in similar ways, however they serve different purposes and are not interchangeable.

Constants are meant to be used to hold values that will not change during the execution of the script. They are available globally: from inside and outside functions alike. Although it is not necessary, many developers choose to use all uppercase when naming constants so that they are easier to spot. The syntax for defining a constant is: define(name, value); where name is a string representing the name of a constant and value is the data to be stored. For example, you could store a custom value for pi using the code: define("PI", 3.14); where PI is the name and 3.14 is the value. To use the constant you simply reference the name you gave it. For example, echo(PI); would display 3.14. The benefit to using a constant rather than hard-coding the value is simplifying updates and improving stability by reducing possible human error.

Variables hold data that will most likely change during the execution of the script. By default, they are only available locally: from the same function or level where they are declared. The syntax for setting a variable is: $name = value; where name represents the alpha-numeric name of the variable and value is the data to be stored. For example, you could store the radius of a circle using the code $radius = 3; where radius is the name of the variable and 3 is the value. To use the value you simply reference the name you gave it preceded by a $. For example, echo($radius); would display 3.

Their usage will be summarised in the following exercise.

Exercise

Our objective is to calculate and display the perimeter of a circle using PHP. The end result should be similar to what you see on screen now.

We will start by creating an empty PHP file. Next we will define a constant for pi (3.14) and a variable for our radius (3). After that we will use the formula 2πr to calculate the perimeter and store it in a variable. Finally we will echo the perimeter along with an explanatory sentence. Notice that the variable is outside of the quotes and they are concatenated (or joined) by a dot.

If you view your file through a local or live server that can process PHP, you should see the desired result.

Screencast URL: To come

No comments:

Post a Comment