×
Author:
Website:
Page title:
URL:
Published:
Last revised:
Accessed:

Constants

Overview

In mathematics and science, a constant is a fixed value or quantity that does not change, such as the value of pi (π) or the speed of light (299 792 458 m/s). Many of these values are also defined as be constants in programming languages like PHP, but they usually only comprise a small subset of the complete range of constants defined for a particular programming language - and PHP is no exception. When you take into account user-defined constants, the possibilities are virtually limitless.

One thing all constants have in common is that, once defined, they cannot be changed. The value of pi can be calculated to an incredible number of decimal places (and has been), but its definition - the ratio of a circle's circumference to its diameter - will not change. And unless the laws of physics themselves - or at least our perceptions of them - undergo some radical change, the speed of light is also safe.

The constants we use with PHP fall into two broad categories: PHP’s built-in constants - of which there are many - and user-defined constants. We’ve already seen some of PHP’s built-in constants elsewhere in this section including PHP_INT_SIZE (which defines the number of bytes used to store an integer value on the current system) and PHP_INT_MAX and PHP_INT_MIN (to find the largest and smallest integer values that can be stored on the current system).

PHP also provides a small number of what it calls “magic constants”. These are not really constants in the true sense, because their value can change, depending on where they are used. The names of magic constants are also case-insensitive. We’ll briefly look at these constants and what they are used for later in this article.

User-defined constants are used for values that will not change over the lifetime of a script, such as configuration settings, database credentials, file paths, error messages, and other application-specific values. Using appropriately named constants to represent values of this nature makes code easier to read and maintain. It also eliminates the possibility of key values being accidently overwritten.

While constants often define numeric values, they can be used to define just about anything, including various system resources. A constant can even store an array of values. Many of PHP’s built-in constants identify the characteristics of the current build of PHP such as the version number (PHP_VERSION), the operating system for which it was built (PHP_OS), or the server application programming interface (SAPI) it is using (PHP_SAPI).

With the exception of class constants (which we’ll be talking about later in this article) the scope of a constant is always global - the value stored in a constant can be accessed from anywhere in a script regardless of where the constant is declared, simply by specifying the name of the constant. Constant names are case sensitive and are (usually) written using uppercase characters, making it easy to distinguish between constants and variables in a script. Unlike variable names, they are not prefixed by the dollar sign ($).

Constants vs. variables

Constants and variables both store data. The main difference between the two is that the value of a constant is fixed and cannot change at runtime (i.e. while the script is running) whereas a variable can change (the names “constant” and “variable” speak for themselves when you think about it). But why not simply use variables for everything? It’s not like we are compelled to change the value of a variable, after all.

We could declare a variable called $pi and assign it the value 3.1415926535898. There is little possibility that we would assign a different value to $pi elsewhere in the script. But suppose we created a variable called $max-value to define some maximum value in our script that should never change.

In a relatively short, stand-alone script this is unlikely to cause a problem. In a much longer script, or one that is worked on by several programmers, there is a chance, however small, that the value stored in $max-value could be overwritten, or the variable itself redefined for a completely different purpose. This cannot happen with a constant. For example:

<?php
const MAX_SIZE = 100;
.
.
.
MAX_SIZE = 120;
// Parse error: syntax error, unexpected token "=" . . .
?>

If we create a constant in our script and attempt to change its value somewhere later in the script, a syntax error message will be generated. The same thing happens if we attempt to assign a value to one of PHP’s built-in constants. Using a constant for a value that should not change over the lifetime of a script eliminates the possibility of that value being overwritten or redefined.

Then there is the question of scope. Any constant declared outside of a class definition automatically has global scope. That means we can access its value from anywhere in our script. The same cannot be said of a variable. Consider the following script:

<?php
$myVal = 5;

function myFunction() {
echo $myVal;
}

myFunction();
// Warning: Undefined variable $myVal . . .
?>

In the above script, the variable $myVal has global scope, but when we attempt to access it from inside myFunction(), a warning is generated telling us that the variable $myVal is undefined. There are of course a couple of possible solutions. For example, we could pass the variable $myVal to myFunction() as an argument. We could also explicitly declare the variable as a global variable inside the function, like this:

<?php
$myVal = 5;

function myFunction() {
global $myVal;
echo $myVal;
}

myFunction();
// 5
?>

Either of these solutions works, and if the value of $myVal is subject to change during the execution of the script, maybe that’s the way to go. But let’s suppose that the value of $myVal is supposed to be constant throughout the script. If we declare it as a constant, the problem of scope immediately goes away. For example:

<?php
const MY_VAL = 5;

function myFunction() {
echo MY_VAL;
}

myFunction();
// 5
?>

Unlike variables, constants do not need to be prefixed with the dollar sign ($), and by convention are named using all uppercase characters, which makes them easy to distinguish from variable names.

Constants should be used when we want to store fixed values that should not be modified elsewhere in a script, and that we want to be accessible from any part of the script regardless of scope. A constant can be declared anywhere in a script (outside of a class) regardless of the scope in which it is declared, and will still be globally accessible.

User-defined constants

User-defined constants can be defined in one of two ways. The first method we will examine requires the use of the const keyword. Using const, we can define a constant that has a scalar value, i.e. a Boolean, integer, floating point, or string value, or a constant array. For example:

<?php
const MY_DOMAIN = "technologyuk.net";
echo "This website's domain name is " . MY_DOMAIN . "."
// This website's domain name is technologyuk.net.
?>

The second method is to use the define() function, which gives us a little more scope than using const because it allows us to define a constant as an arbitrary expression. The define() function takes three arguments. The first argument is the name of the constant, and the second argument is the value that the constant represents. The define() function returns true if it succeeds and false if it fails.

The third (optional) argument to define() is a Boolean value that, if used, determines whether or not the constant name is case-insensitive. If set to true, the constant name will be case-insensitive. If set to false (the default value), the name will be case-sensitive.

Constant names must start with a letter or an underscore. Other than that, the name can contain any number of letters, numbers or underscores. By convention, constant names are written in all uppercase characters, with individual words separated by an underscore. It is possible to name a constant using lower case characters, or even mixed-case characters, but this is not considered good practice.

Using define(), it is even possible to name a constant using a PHP reserved word, although this is also not considered to be good practice. The only way to retrieve the value of a constant so named is by using the constant() function. For example:

<?php
define("break", "Take a break!");
echo constant("break");
// Take a break!
?>

As well as being slightly more flexible than using the const keyword to create a constant, the define() function has the added advantage that it can be used anywhere in a script, whereas const can only be used be used in the global scope or within a class definition. We can’t use const inside a code block such as a function or a loop.

Constants declared using define() are globally accessible regardless of where they are declared, so a constant declared inside a function or a loop using define() is accessible from anywhere in the script.

Another advantage of using the define() function is that, whereas constants declared using the const keyword are created at compile time, constants declared using define() are not created until the script actually runs. This means that conditional statements can be used within a script to determine whether or not a constant will be defined. For example:

<?php
define("MY_WEBSITE", "www.technologyuk.net");
.
.
.
if(!defined("MY_WEBSITE")) {
define("MY_WEBSITE", "www.technologyuk.net");
echo "The constant MY_WEBSITE has been created.";
}
else {
echo "The constant MY_WEBSITE already exists.";
}
// The constant MY_WEBSITE already exists.
?>

In this example, we have defined the constant MY_WEBSITE at the beginning of the script. Later in the script we use an if . . . else conditional statement that checks whether this constant has already been defined using the defined() function.

If the constant does not already exist it will be created, and a message to that effect is displayed. Otherwise, a message telling us that the constant already exists is displayed. If we comment out the first line of code in this example, the constant will be created:

<?php
// define("MY_WEBSITE", "www.technologyuk.net");
.
.
.
if(!defined("MY_WEBSITE")) {
define("MY_WEBSITE", "www.technologyuk.net");
echo "The constant MY_WEBSITE has been created.";
}
else {
echo "The constant MY_WEBSITE already exists.";
}
// The constant MY_WEBSITE has been created.
?>

The ability to define constants dynamically using define() is useful when certain values must remain constant throughout the lifetime of a script but are not known before the script is executed. For example, we might write a script that uses constants to hold details of the platform on which the script is running. The values stored in these constants won’t change during the execution of the script, but they will not be known to us before the script runs.

Arrays as constants

Prior to the release of version 7.0 of PHP, it was only possible to use the const keyword to define an array as a constant. As of version 7.0, a constant can be defined an array of scalar values using the define() function. We could, for example, create an array constant to hold the days of the week, the months of the year, or a collection of default configuration settings for an application. We define an array constant using define() in the same way as any other constant. For example:

<?php
define('SHORT_DAYS', [
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat",
"Sun"
]);
for($i = 0; $i < count(SHORT_DAYS); $i++) {
echo SHORT_DAYS[$i] . "<br>";
}
// Mon
// Tue
// Wed
// Thu
// Fri
// Sat
// Sun
?>

We can just as easily create an array constant using an associative array, i.e. an array in which each array element consists of a key-value pair. The following example demonstrates the principle:

<?php
define('RGB_VALUES', [
"Red" => "#ff0000",
"Green" => "#00ff00",
"Blue" => "#0000ff",
]);
foreach(RGB_VALUES as $color) {
echo $color . "<br>";
}
// #ff0000
// #00ff00
// #0000ff
?>

As you can see from the above examples, the elements of an array constant can be accessed in the same way as those of any other array using a numerical array subscript or a named key, depending on how the array is defined. The only difference is that we can’t change the values stored in the array. Use array constants for managing related values such as configuration settings or preset limits that will not change during the execution of a script.

Class constants

We have briefly touched on the subject of classes and objects in the article “Variables and Datatypes” in this section, so you should at least have an idea of what these terms mean. Just to recap, an object is a collection of properties - the values associated with an object that describe its state, and methods - the functions provided by the object to access and manipulate its properties. A class is essentially the template used to create an object.

Class constants can be thought of as class properties that, once defined, cannot be changed. An object that is created as an instance of a particular class will of course inherit any class constants defined for that class along with its other properties, although those same class constants can be redefined by a child class unless (as of PHP version 8.0) a class constant has been defined as final in the parent class.

A class constant may be any scalar value, or an array of scalar values. Class constants must be defined using the const keyword. Attempting to define a class constant using the define() function will result in an error. The following example demonstrates how we might declare a constant in a class:

<?php
class Circle {
const PI = 3.14159;
private $circ;
private $area;

public function __construct($radius) {
$this->circ = $radius * 2.0 * self::PI;
$this->area = $radius**2 * self::PI;
}
public function getCirc() {
return $this->circ;
}
public function getArea() {
return $this->area;
}
}

$radius = 5.0;
$units = "metres";
$circle = new Circle($radius);

echo "For a circle of radius $radius $units:<br><br>";
echo "The circumference is " . $circle->getCirc() . " $units.<br>";
echo "The area is " . $circle->getArea() . " $units.<br>";
echo "The value used for PI is: " . $circle::PI . ".";

// For a circle of radius 5 metres:
//
// The circumference is 31.4159metres.
// The area is 78.53975metres.
// The value used for PI is: 3.14159.
?>

Note that by default, a class constant is visible outside the class in which it is defined. We don’t need to explicitly use the public keyword. As you can see from the example, we can access the constant from outside the class using the name of the class variable followed by the scope resolution operator (::) and the name of the constant. As you can also see, in order to access a class constant from inside the class, we use self:: followed by the name of the constant.

As of PHP version 7.1.0, we can precede a class constant with a visibility modifier such as public, protected or private. Like other class members, class constants members declared public can be accessed from anywhere in the current namespace (we’ll address the subject of namespaces in another article. For now, we’ll assume all code is written in the global namespace).

Class constants defined using the protected keyword can be accessed only within the class itself, and by parent and child classes. Class constants defined using the private keyword can only be accessed by the class that defines the constant. If we don’t want a class constant to be visible outside of the class it is defined in, we should declare it as private. Any subsequent attempt to access the constant from outside the class will result in an error. For example:

<?php
class Circle {
public const PI = 3.14159;
.
.
.
}

echo Circle::PI;

// Fatal error: Uncaught Error: Cannot access private constant Circle::PI . . .
?>

We can also use the final keyword, introduced with PHP version 8.1, to ensure that a child class cannot redefine a constant declared in its parent class. This is useful if we have a critical constant value that we want to protect, and helps to prevent unwanted code modification. For example:

<?php
class Circle {
final public const PI = 3.141592653589793;
.
.
.
}

class Circle2 extends Circle {
public const PI = 3.141593;
.
.
.
}

// Fatal error: Circle2::PI cannot override final constant Circle::PI . . .
?>

Before we leave the subject of class constants, it is worth noting that PHP version 8.3.0, released in November of 2023, was a major update that introduced a number of new features to the language including support for declaring a type for class constants. Since the highest version of PHP currently provided by the latest versions of XAMPP for Windows or Linux is PHP 8.2.12, we are for now only covering features supported prior to PHP 8.3.0.

Core predefined constants

PHP provides a large number of predefined constants, several of which we have already mentioned elsewhere. The core predefined constants are, as the name suggests, are defined by the PHP core, which includes PHP itself, the Zend engine, and Server Application Programming Interface (SAPI) modules. The table below lists the current (at the time of writing) PHP core predefined constants and gives a brief summary of each (the descriptions shown are taken from the PHP Group’s online manual for PHP 8.4).



.
Core Predefined Constants
ConstantDescription
PHP_VERSION (string)The current PHP version as a string in "major.minor.release[extra]" notation.
PHP_MAJOR_VERSION (int)The current PHP "major" version as an integer (e.g., int(5) from version "5.2.7-extra").
PHP_MINOR_VERSION (int)The current PHP "minor" version as an integer (e.g., int(2) from version "5.2.7-extra").
PHP_RELEASE_VERSION (int)The current PHP "release" version as an integer (e.g., int(7) from version "5.2.7-extra").
PHP_VERSION_ID (int)The current PHP version as an integer, useful for version comparisons (e.g., int(50207) from version "5.2.7-extra").
PHP_EXTRA_VERSION (string)The current PHP "extra" version as a string (e.g., '-extra' from version "5.2.7-extra"). Often used by distribution vendors to indicate a package version.
ZEND_THREAD_SAFE (bool)Indicates whether the current build of PHP is thread safe.
ZEND_DEBUG_BUILD (bool)Indicates whether the current build of PHP is a debug build.
PHP_ZTS (bool)Alias of ZEND_THREAD_SAFE. Indicates whether the current build of PHP is thread safe.
PHP_DEBUG (bool)Alias of ZEND_DEBUG_BUILD. Indicates whether the current build of PHP is a debug build.
DEBUG_BACKTRACE_PROVIDE_OBJECT (int)Populate the "object" index.
DEBUG_BACKTRACE_IGNORE_ARGS (int)Don't include the argument information for functions in the stack trace.
PHP_MAXPATHLEN (int)The maximum length of filenames (including path) supported by this build of PHP.
PHP_OS (string)The operating system PHP was built for.
PHP_OS_FAMILY (string)The operating system family PHP was built for. One of 'Windows', 'BSD', 'Darwin', 'Solaris', 'Linux' or 'Unknown'. Available as of PHP 7.2.0.
PHP_SAPI (string)The Server API for this build of PHP. See also php_sapi_name().
PHP_EOL (string)The correct 'End Of Line' symbol for this platform.
PHP_INT_MAX (int)The largest integer supported in this build of PHP. Usually int(2147483647) in 32 bit systems and int(9223372036854775807) in 64 bit systems.
PHP_INT_MIN (int)The smallest integer supported in this build of PHP. Usually int(-2147483648) in 32 bit systems and int(-9223372036854775808) in 64 bit systems. Usually, PHP_INT_MIN === ~PHP_INT_MAX.
PHP_INT_SIZE (int)The size of an integer in bytes in this build of PHP.
PHP_FLOAT_DIG (int)Number of decimal digits that can be rounded into a float and back without precision loss. Available as of PHP 7.2.0.
PHP_FLOAT_EPSILON (float)Smallest representable positive number x, so that x + 1.0 != 1.0. Available as of PHP 7.2.0.
PHP_FLOAT_MIN (float)Smallest representable positive floating point number. If you need the smallest representable negative floating point number, use - PHP_FLOAT_MAX. Available as of PHP 7.2.0.
PHP_FLOAT_MAX (float)Largest representable floating point number. Available as of PHP 7.2.0.
DEFAULT_INCLUDE_PATH (string)-
PEAR_INSTALL_DIR (string)-
PEAR_EXTENSION_DIR (string)The default directory where to look for dynamically loadable extensions (unless overridden by extension_dir). Defaults to PHP_PREFIX (or PHP_PREFIX . "\\ext" on Windows).
PHP_PREFIX (string)The value --prefix was set to at configure. On Windows, it is the value --with-prefix was set to at configure.
PHP_BINDIR (string)The value --bindir was set to at configure. On Windows, it is the value --with-prefix was set to at configure.
PHP_SBINDIR (string)The value --sbindir was set to at configure. On Windows, it is the value --with-prefix was set to at configure. Available as of PHP 8.4.0.
PHP_BINARY (string)Specifies the PHP binary path during script execution.
PHP_MANDIR (string)Specifies where the manpages were installed into.
PHP_LIBDIR (string)-
PHP_DATADIR (string)-
PHP_SYSCONFDIR (string)-
PHP_LOCALSTATEDIR (string)-
PHP_CONFIG_FILE_PATH (string)-
PHP_CONFIG_FILE_SCAN_DIR (string)-
PHP_SHLIB_SUFFIX (string)The build-platform's shared library suffix, such as "so" (most Unixes) or "dll" (Windows).
PHP_FD_SETSIZE (int)The maximum number of file descriptors for select system calls. Available as of PHP 7.1.0.
__COMPILER_HALT_OFFSET__ (int)-
true (bool)Used to express a truth value (true)
false (bool)Used to express a truth value (false).
null (null)Has only one value (null). Undefined and unset() variables will resolve to the value null.
PHP_WINDOWS_EVENT_CTRL_C (int)A Windows CTRL +C event. Available as of PHP 7.4.0 (Windows only).
PHP_WINDOWS_EVENT_CTRL_BREAK (int)A Windows CTRL +BREAK event. Available as of PHP 7.4.0 (Windows only).
PHP_CLI_PROCESS_TITLE (bool)Indicates whether the setting and getting of the process title is available. Available only under the CLI SAPI.
STDERR (resource)An already opened stream to stderr. Available only under the CLI SAPI.
STDIN (resource)An already opened stream to stdin. Available only under the CLI SAPI.
STDOUT (resource)An already opened stream to stdout. Available only under the CLI SAPI.
Error Reporting Constants
ConstantDescription
E_ERROR (int)Fatal run-time errors. These indicate errors that can not be recovered from, such as a memory allocation problem. Execution of the script is halted. Value of the constant: 1
E_WARNING (int)Run-time warnings (non-fatal errors). Execution of the script is not halted. Value of the constant: 2
E_PARSE (int)Compile-time parse errors. Parse errors should only be generated by the parser. Value of the constant: 4
E_NOTICE (int)Run-time notices. Indicate that the script encountered something that could indicate an error, but could also happen in the normal course of running a script. Value of the constant: 8
E_CORE_ERROR (int)Fatal errors that occur during PHP's initial startup. This is like an E_ERROR, except it is generated by the core of PHP. Value of the constant: 16.
E_CORE_WARNING (int)Warnings (non-fatal errors) that occur during PHP's initial startup. This is like an E_WARNING, except it is generated by the core of PHP. Value of the constant: 32.
E_COMPILE_ERROR (int)Fatal compile-time errors. This is like an E_ERROR, except it is generated by the Zend Scripting Engine. Value of the constant: 64.
E_COMPILE_WARNING (int)Compile-time warnings (non-fatal errors). This is like an E_WARNING, except it is generated by the Zend Scripting Engine. Value of the constant: 128.
E_USER_ERROR (int)User-generated error message. This is like an E_ERROR, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: 256.

Warning: Usage of this constant with trigger_error() is deprecated as of PHP 8.4.0. It is recommended to either throw an Exception or call exit() instead.
E_USER_WARNING (int)User-generated warning message. This is like an E_WARNING, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: 512.
E_USER_NOTICE (int)User-generated notice message. This is like an E_NOTICE, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: 1024.
E_RECOVERABLE_ERROR (int)Legacy engine "exceptions" which correspond to catchable fatal error. Similar to Error but must be caught via a user defined error handler (see set_error_handler()). If not handled, this behaves like E_ERROR. Value of the constant: 4096.

Note: This error level is effectively unused, the only case where this can happen is when interpreting an object as a bool fails. This can only happen for internal objects. The most common example, prior to PHP 8.4.0, is using a GMP instance in a conditional.
E_DEPRECATED (int)Run-time deprecation notices. Enable this to receive warnings about code that will not work in future versions. Value of the constant: 8192.
E_USER_DEPRECATED (int)User-generated deprecation message. This is like an E_DEPRECATED, except it is generated in PHP code by using the PHP function trigger_error(). Value of the constant: 16384.
E_ALL (int)
E_STRICT (int)Run-time suggestions emitted by PHP about the executed code to ensure forward compatibility. Value of the constant: 2048.

Warning: This error level is unused, and has been deprecated as of PHP 8.4.0.

Mathematical constants

PHP also provides a number of predefined mathematical constants that are always available as part of the PHP core, which includes PHP itself, the Zend engine, and Server Application Programming Interface (SAPI) modules. The table below lists the current (at the time of writing) PHP mathematical constants and gives a brief summary of each (the descriptions shown are taken from the PHP Group’s online manual for PHP 8.4).



Predefined Mathematical Constants
ConstantDescription
M_PI (float)Approximation of the number π (pi) (3.14159265358979323846).
M_E (float)Approximation of Euler's number e (2.7182818284590452354).
M_LOG2E (float)Approximation of log2(e) (1.4426950408889634074).
M_LOG10E (float)Approximation of log10(e) (0.43429448190325182765).
M_LN2 (float)Approximation of ln(2) (0.69314718055994530942).
M_LN10 (float)Approximation of ln(10) (2.30258509299404568402).
M_PI_2 (float)Approximation of π/2 (1.57079632679489661923).
M_PI_4 (float)Approximation of π/4 (0.78539816339744830962).
M_1_PI (float)Approximation of 1/π (0.31830988618379067154).
M_2_PI (float)Approximation of 2/π (0.63661977236758134308).
M_SQRTPI (float)Approximation of sqrt(π) (1.77245385090551602729).
M_2_SQRTPI (float)Approximation of 2/sqrt(π) (1.12837916709551257390).
M_SQRT2 (float)Approximation of sqrt(2) (1.41421356237309504880).
M_SQRT3 (float)Approximation of sqrt(3) (1.73205080756887729352).
M_SQRT1_2 (float)Approximation of 1/sqrt(2) (0.70710678118654752440).
M_LNPI (float)Approximation of ln(π) (1.14472988584940017414).
M_EULER (float)Approximation of Euler's constant γ (0.57721566490153286061).
IEEE 754 floating point constants
ConstantDescription
NAN (float)Not A Number.
INF (float)Infinity.
Rounding constants
Note: As of PHP 8.4.0, it is recommended to use the RoundingMode enum instead.
ConstantDescription
PHP_ROUND_HALF_UP (int)Rounding half away from zero.
PHP_ROUND_HALF_DOWN (int)Rounding half toward zero.
PHP_ROUND_HALF_EVEN (int)Round halves to even numbers.
PHP_ROUND_HALF_ODD (int)Round halves to odd numbers.

Magic constants

PHP provides a number of magic constants that are not really constants in the normally accepted sense of the word because the value they represent can vary according to where they are used. Unlike normal constants, whose value is resolved at runtime, the value of a magical constant is determined when the script is compiled.

All of the currently defined magic constants are case-insensitive, and all are easily recognisable as magic constants because they have a double underscore prefix and suffix. The table below lists the current (at the time of writing) PHP magic constants and gives a brief summary of each (the descriptions shown are taken from the PHP Group’s online manual for PHP 8.4).



Magic Constants
ConstantDescription
__LINE__The current line number of the file.
__FILE__The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__The function name, or {closure} for anonymous functions.
__CLASS__The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar). When used inside a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__The class method name.
__PROPERTY__Only valid inside a property hook. It is equal to the name of the property.
__NAMESPACE__The name of the current namespace.

Constant-related functions

PHP provides several functions that are specifically related to constants. The one with which you will already be familiar is the define() function which we can use to dynamically declare a constant. Since we have already seen how define() is used, we will not be saying anything further about it here.

Another constant-related function, and one which we briefly mentioned earlier, is the constant() function. This function takes one argument - the name of a constant - and returns the value of the constant. It is useful if you want to retrieve the value of a constant but do not know its name because the constant’s name is stored in a variable or is returned by a function. The following example shows how the constant() function might be used:

<?php
const MY_WEBSITE = "technologyuk.net";
echo constant("MY_WEBSITE");
// technologyuk.net
?>

Of course, in this case we could just as easily obtain the same output using echo or print_r() with the constant name, assuming we know it. For example:

<?php
define("MY_WEBSITE", "technologyuk.net");
echo MY_WEBSITE;
// technologyuk.net
?>

The same thing is not true if we store the name of a constant in a variable. If the name of a constant is stored in a variable, we cannot use echo or print_r() alone to output its value. We have to use the constant() function as demonstrated by the following example.

<?php
define("MY_WEBSITE", "technologyuk.net");
$website = "MY_WEBSITE";
echo "$website <br>";
echo constant($website);
// MY_WEBSITE
// technologyuk.net
?>

Any attempt to use constant() to retrieve the value of a constant that has not been defined will result in an error, as the following example demonstrates:

<?php
$website = "technologyuk.net";
echo constant($website);
// Fatal error: Uncaught Error: Undefined constant "technologyuk.net" . . .
?>

This could cause a problem if we are dealing with a variable or a value returned by a function that we think might contain the name of a constant but do not know for certain, which brings us nicely to the next constant-related function. The defined() function, which we have also briefly touched upon in this article, accepts the name of a constant as its argument and returns true or false, depending on whether or not the name passed to it represents a defined constant.

We can use the defined() function together with the constant() function to handle potentially undefined constants without triggering a PHP error by checking whether or not a constant has been defined before attempting to retrieve its value. The following example demonstrates the principle:

<?php
define("MY_WEBSITE", "technologyuk.net");
$website = "MY_WEBSITE";
if(defined($website)) {
echo constant($website);
}
else {
echo "Constant is undefined.<br>";
}
// technologyuk.net
?>

The last constant-related function we want to mention here is the get-defined_constants() function. This function returns an associative array containing the names and values of all constants currently defined, including user-defined constants and those created by extensions. It takes one Boolean argument (categorise) that defaults to false. If set to true, the list of defined constants will be organised by category within a multidimensional array. The following code can be used to generate a categorised output:

<?php
print_r(get_defined_constants(true));
?>