In this tutorial, you will learn about how to use constants for storing fixed values in PHP.
PHP constants are names or identifiers that can not be changed during the execution of the entire program (except Magic constant). PHP constants define in two ways:
- Using define function
- Using const keyword
PHP constants are similar to the PHP variables except that they cannot be changed or undefined once declared. They remain fixed for the entire program.
Naming convention of PHP Constant
The naming convention of the PHP constant follows the same rules of the PHP variable.
- PHP constant names start with
$
and followed by variable names. - All the constant name in PHP only contain alpha-numeric characters and underscore (A-Z, a-z, 0-9, and _ )
- A constant in PHP must start with a letter or underscore.
- The name cannot start with numbers.
- A PHP constant cannot contain space.
Note: As per convention, PHP constant name should be defined in uppercase letters.
PHP Constant: define()
Generally, PHP constants is defined using define()
function. This function accepts two arguments; the name of the constant and it’s value. Once defined, constants can be accessed anytime, anywhere in a program just by referring to its name. Below is the syntax of PHP constants.
PHP Constants Syntax
define(name,value,case-insensitive)
It also accepts the third argument which is case-insensitive which is false by default.
PHP constant Example
<?php // Defining constant define("SITE_URL", "https://tutorialsbook.com/"); // Using constant echo 'Thank you for visiting - ' . SITE_URL; ?>
Output
In the above example, we have defined one PHP constant named SITE_URL and stored value in it and later on we have printed the browser using PHP echo statement.
PHP Constant: const keyword
Another way to define constant in PHP is using const
keyword which has been introduced by PHP newly. This keyword defines constants at compile time. It’s a language construct, not a function. The constants defined using the const
keyword are case-insensitive.
<?php const MESSAGE="Hello const by Tutorialsbook PHP"; echo MESSAGE; ?>