Like variables, PHP constants can store values. However, once a constant has been created, its value cannot be changed while the script runs.
Constants are useful for storing data that doesn’t (and shouldn’t) change while the script is running. Common examples of such data include configuration settings (such as database usernames and passwords) and fixed strings of text to display to visitors (such as “Please login to continue”).
Constants are also often used to represent integer values with special meanings in a particular context, such as error codes and flags.

How to create a constant

PHP constant names follow the same rules as PHP variable names. The only difference is that constant names don’t start with a $ (dollar) symbol, while variable names do.
PHP constant names are case-sensitive. Usually, constant names use all-uppercase letters, with underscores to separate words within the name.
To create a PHP constant, use the following syntax:
define( "CONSTANT_NAME", constant_value );

CONSTANT_NAME” is a string holding the name of the constant to create, while constant_value is the value that the constant will hold. Here are a couple of examples:

<?php
define( "HELLO", "Hello, world!" );
define( "WIDGET_PRICE", 29.99 );

?>

The first line of code creates a PHP constant called HELLO with a string value of “Hello, world!”, while the second line creates a constant called WIDGET_PRICE with a numeric value of 29.99.
PHP constants can only hold scalar values — these include numbers, strings of text, and boolean values. They can’t hold arrays or objects, like variables can.
You can only define a constant once within a script. If you try to redefine a constant, the PHP engine generates an error.

Using constants in PHP

You access a PHP constant in exactly the same way as you use a variable. To use a constant’s value, simply write the constant name. The following example displays the values of the HELLO and WIDGET_PRICEconstants:
<?php
echo HELLO;
echo WIDGET_PRICE;
?>

Predefined constants

PHP features a large number of built-in, predefined constants holding various useful values. Some of these are always available, while other constants become available when certain PHP extensions are enabled. For example, the PHP constant M_PIholds the mathematical constant Pi. The following code displays this value:
<?php
echo M_PI;
?>

Another useful predefined constant is PHP_VERSION, which holds the current version of the running PHP engine:
<?php
echo PHP_VERSION;

?>
The PHP website has a list of built-in predefined constants.

0 comments:

Post a Comment

 
Top
Blogger Template