Constants

You can define constants in your program. A constant, like its name implies, cannot change its value during the execution of your program. It's defined using the define() function, which takes the name of the constant as the first parameter and the values as the second parameter. The definition of a constant is global and can be defined as any simple (scalar) data type, such as a string or number. You can get the value of a constant by simply specifying its name, as shown in Example 3-20, or by using the constant function. Unlike how you handle variables, you should not put the dollar sign ($) before a constant.

If the name of a constant is stored in a variable or the result of a function, you'll need to use the function constant(name) to return the constant's value. It takes a parameter as the name of the constant and returns its value. Or you could use get_defined_ constants() to return a list (as an array) of all your defined constants. If you're unsure about the arguments to a function, you can search using the PHP site (http:// www.php.net) to find function parameters and return values.

These are the differences between constants and variables:

• It's common practice to capitalize a variable name for constants.

• Constants do not have a dollar sign ($) at the start of their names.

• Constants can be defined only by using the define function, not by simple assignment.

• Constants are defined and accessed globally.

• Constants cannot be redefined or undefined once they have been set.

• Constants can evaluate only to scalar values.

Example 3-20 demonstrates how to use a constant in your program.

Example 3-20. Using a constant in your program <?php define("HELLO", "Hello world! "); echo HELLO; // outputs "Hello world!"

$constant_name = "HELLO";

echo constant($constant_name); ?>

outputs:

Hello world! Hello world!

Constants are useful for values that you need to make sure don't change, such as a configuration file location.

If you use an undefined constant, PHP assumes that you mean the name of the constant itself, just as if you called it as a string—for example, CONSTANT as opposed to "CONSTANT". If the define line of Example 3-20 is commented out, for example:

// define ("HELLO", "Hello world!");

the output becomes:

HELLO

You'll also see a warning if PHP is configured to issue notices.

Was this article helpful?

0 0

Post a comment