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 |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |