What is the constant() function in PHP?

The constant() function returns the value of a constant when you have the name of the constant as a string. It is useful when the constant name is stored in a variable or created at run time.

<?php
define("SITE_NAME", "Tutorials Class");

class App {
    const VERSION = "2.0";
}

echo constant("SITE_NAME") . "<br>";

$name = "SITE_NAME";
echo constant($name) . "<br>";

echo constant("App::VERSION");
?>

Output:

Tutorials Class - Output Window

Tutorials Class
Tutorials Class
2.0

If the constant does not exist, PHP 8 throws an Error. Check it first with defined(). Read PHP Constants for the basics.


Learn more about the similar topics:
Tutorials
PHP Variables
PHP Data Types
PHP Constants
PHP isset() Function
PHP empty() Function
PHP is_null() Function
Exercises & Assignments
Write a program to print “Hello PHP” using variable
Write a program to print a string using echo+variable.
Write a program to print two variables in single echo
Interview Questions & Answers
How to check if a variable is empty in PHP?
Is PHP a case sensitive language?
What are the different data types in PHP?
How to define a Constant in PHP?
What is the difference between $var and $$var in PHP?
Which special characters are allowed in PHP variable names?
Can we print multiple variables in a single echo statement in PHP?