Searching...
Sunday 16 June 2013

PHP Basics - Part 5 :: Constants


A constant is a value that cannot be modified throughout the execution of a program. Constants are particularly useful when working with values that definitely will not require modification, such as Pi (3.141592) or the number of feet in a mile (5,280)[I didn't knew that]. Once a constant has been defined, it cannot be changed (or redefined) at any other point of the program. Constants are defined using the define() function (more about functions).

Defining a Constant

The define() function defines a constant by assigning a value to a name. Its prototype follows:

boolean define(string name, mixed value [, bool case_insensitive])

If the optional parameter case_insensitive is included and assigned TRUE, subsequent references to the constant will be case insensitive. Consider the following example in which the mathematical constant Pi is defined:

define("PI", 3.141592);

The constant is subsequently used in the following listing:

printf("The value of Pi is %f", PI);
$pi2 = 2 * PI;
printf("Pi doubled equals %f", $pi2);

This code produces the following results:

The value of pi is 3.141592.
Pi doubled equals 6.283184.

There are several points to note regarding the previous listing. The first is that constant references are not prefaced with a dollar sign. The second is that you can’t redefine or undefine the constant once it has been defined (e.g., 2*PI); if you need to produce a value based on the constant, the value must be stored in another variable. Finally, constants are global; they can be referenced anywhere in your script.

Now that you have understood the concepts of variables and constants, you can now move on to our next topic expressions. In expressions the variables are used hand-on-hand to the constants.

0 comments:

Post a Comment

 
Back to top!