PHP constant() Function

What is PHP constant() Function?

If you want to get a constant name, use PHP constant() function.




The function has one parameter which is required-

CONSTANT_NAME (Required): Name of the constant.

Return Values:

The function returns-

  • Value of the constant – if the constant has been defined.
  • Fatal Error (Undefined error) –  if the constant has not been defined.


Example 1:

define("SITENAME", "Schools of Web");
echo constant("SITENAME");


Schools of Web


The function constant() displays the constant name that was defined previously.

Example 2:

echo constant("SITEURL");


Fatal error: Uncaught Error: Undefined constant “SITEURL” in D:\xampp\htdocs\php\constant.php:2 Stack trace: #0 D:\xampp\htdocs\php\constant.php(2): constant(‘SITEURL’) #1 {main} thrown in D:\xampp\htdocs\php\constant.php on line 2


The constant() function is trying to display such a constant that has not been defined, so, PHP throws an error.

Example 3:

$content = "CONTENT";

define("SITE_" . $content, "Web Development");
echo constant("SITE_" . $content);


Web Development

Practical Usages of constant() Function:

  • To print a constant.
  • To retrieve a constant value but you don’t know its name (it may be stored in a variable or it is returned by a function). Check example 3.

PHP Version Support:

PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8

Summary: PHP constant() Function

constant() is a straightforward and short built-in miscellaneous type function in PHP which help provide constant name of a defined constant.