constant
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
Returns the value of a constant
Description
Return the value of the constant indicated by name.
constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function.
This function works also with class constants and enum cases.
Parameters
nameThe constant name.
Noteconstant()takes the name as an ordinarystringand does not resolve it against the current namespace: the name is looked up in the global namespace, so an unqualified name may silently return a different constant from the one the same bare identifier would refer to. To retrieve the value of a constant declared in a namespace, the namespace must be part of the name, as inconstant('My\Namespace\MYCONST')orconstant(__NAMESPACE__ . '\MYCONST'). Because the name is a plain string, aliases introduced byusestatements and thenamespace\prefix are not applied to it. In a double-quoted string the namespace separators must be escaped, as in"My\\Namespace\\MYCONST". The namespace part of the name is case-insensitive, the constant name is not.
Return Values
Returns the value of the constant.
Errors/Exceptions
If the constant is not defined, an Error exception is thrown. Prior to PHP 8.0.0, an E_WARNING level error was generated in that case.
Changelog
| Version | Description |
|---|---|
| 8.0.0 | If the constant is not defined, constant() now throws an Error exception; previously an E_WARNING was generated, and null was returned. |
Examples
Using constant() with Constants
<?php
define("MAXSIZE", 100);
echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line
interface bar {
const test = 'foobar!';
}
class foo {
const test = 'foobar!';
}
$const = 'test';
var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"
?>Using constant() with Enum Cases (as of PHP 8.1.0)
<?php
enum Suit
{
case Hearts;
case Diamonds;
case Clubs;
case Spades;
}
$case = 'Hearts';
var_dump(constant('Suit::'. $case)); // enum(Suit::Hearts)
?>See Also
define()defined()get_defined_constants()- The section on Constants