Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

constant

Returns the value of a constant by its name in a string.

Syntax

constant(string $name): mixed

Parameters

ParameterTypeDescription
$namestringThe constant name; for a class constant, `Class::NAME`.

Return value

mixedThe value of the constant.

Examples

A constant name in a variable:

<?php
 
class Status
{
    public const ACTIVE = 'active';
    public const BLOCKED = 'blocked';
}
 
$name = 'BLOCKED';
 
echo constant('Status::' . $name), ' ', constant('E_USER_ERROR');

Output:

blocked 256

Notes

If the constant does not exist, the function throws an Error. For a set of related values an enum is handier.

See also

  • define — Creates a constant at run time.
  • defined — Checks whether a constant exists.
  • call_user_func — Calls a function held in a variable.

Related recipes

In the tutorial

  • Constants — Constants in PHP — const and define, naming rules, built-in and magic constants.

Thanks for reading!

Donate to the site — we work hard for you.