PHP Constants
PHP Constants
A PHP constant is
an identifier name for a simple value. As the name suggests, the value cannot
change during the execution of the script (except for magic
constants, which aren't constants).
- It's case-sensitive.
- By convention, any constant identifiers are always uppercase.
- Superglobals, the scope of a constant is global. Constants can be accessed from anywhere in a script without regard to scope.
- The name of a constant follows the same rules as any label in PHP.
- A valid
constant name starts with a letter or underscores, followed by any letters,
numbers, or underscores. As a regular expression, it would be expressed like
this:
^[a-zA-Z_\x80-\xff][a-zA-Z0-9_\x80-\xff]*$
- Constants can be defined by using the const keyword, or the define()-function.
- Use the const keyword, only scalar data type (bool, int, float, and string) expressions and constant arrays containing only scalar data type expressions are accepted. It is possible to define constants as a resource, but they should be avoided, as they can cause unexpected results.
- The value of a constant is accessed simply by specifying its name. Unlike variables, a constant is not started with a $.
- It can also be possible to use the constant() function to read a constant's value if the constant's name is obtained dynamically.
- Constants and global
variables are in a different namespace. Example true and $TRUE are generally
different.
Example 1: Defining
Constants
<?php
define("CONSTANT", "How are you?.");
echo CONSTANT; // outputs "How are
you?"
?>
Example 2: Defining
Constants using the const keyword.
<?php
//
scalar value
const CONSTANT = 'How are you?';
echo CONSTANT;
//
Scalar data type expression
const ANOTHER_CONST = CONSTANT.'; Goodbye World';
echo ANOTHER_CONST;
const NUMBERs = array('one', 'two', 'three');
echo NUMBERs[2]; // outputs
"three"
//
Constant arrays
define('NUMBERs', array(
'one',
'two',
'three'
));
echo NUMBERs[0]; // outputs
"one"
?>
Caution: They cannot be declared constants
using define(), constants
defined using the const keyword inside functions, loops, if statements, or
try/catch blocks it
must be declared at the top-level scope because they are defined at compile
time.
PHP provides a
large number of predefined constants to any script which it runs.
Many of these constants, are created by various extensions, and will only be
present when those extensions are available, either via dynamic loading or they
have been compiled.
The basic difference
between constants and variables are:
- Constants do not have to use a dollar sign ($) before them.
- Constants are defined and accessed anywhere without regard to variable scoping rules.
- Constants do not have to be redefined or undefined once they have been assigned.
- Constants may only evaluate scalar data type values or arrays.
Leave a comment
Commanted On: 06-09-22
Thank you!!