PHP Constants
• A constant is an identifier (name) for a simple value. The constant value cannot be
changed during the script.
• By default a constant is case-sensitive.
• By convention, constant identifiers are always uppercase.
• A valid constant name starts with a letter or underscore (no $ sign before the
constant name).
• If you have defined a constant, it can never be changed or undefined.
• Note: Unlike variables, constants are automatically global across the entire script.
Set a PHP Constant
• To set a constant, use the define() function –
• It takes three parameters: The first parameter defines the name of the constant, the
second parameter defines the value of the constant, and the optional third parameter
specifies whether the constant name should be case-insensitive.
• Default is false.
• The example below creates a case-sensitive constant, with the value of "hello world".
Example:
<?php
define("GREETING", "hello!");
echo GREETING;
?>
constant() function
• As indicated by the name, this function will return the value of the constant.
• This is useful when you want to retrieve value of a constant, but you do not know its
name, i.e. It is stored in a variable or returned by a function.
<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Differences between constants and variables are
• There is no need to write a dollar sign ($) before a constant, where as in Variable one
has to write a dollar sign.
• Constants cannot be defined by simple assignment, they may only be defined using
the define() function.
• Constants may be defined and accessed anywhere without regard to variable
scoping rules.
• Once the Constants have been set, may not be redefined or undefined.
Post a Comment
If you have any doubts, Please let me know
Thanks!