How to make a PHP constant

"Learn how to create a constant in PHP with an example of how to use it for better code organization and maintainability."

Creating a PHP Constant

A constant is an identifier (name) for a simple value. The value cannot be changed during the execution of the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). To create a constant, use the define() function.

define("CONSTANT_NAME", "value");

The example below creates a constant with a case-sensitive name and value:

define("GREETING", "Welcome to W3Schools.com!");

Once a constant is defined, it can never be changed or undefined. Constants are global across the entire script.

To get the value of a constant, use the constant() function. The example below will output "Welcome to W3Schools.com!":

echo constant("GREETING");

Note that constant() is case-sensitive, so the constant name must be in the same case as when it was defined.

PHP also provides a few magical constants that change depending on where they are used. For example, the value of __LINE__ depends on the line that it's used on in your script:

echo "This is line " . __LINE__ . " of the file " . __FILE__;

The output of the code above could be:

This is line 16 of the file C:webfoldermyfile.php

To view a list of all the magical constants, visit the PHP manual.

Answers (0)