Curriculum
In this lesson, you’ll learn about PHP constants and how to define them with the define() method and the const keyword.
A constant is merely a term that has a single value associated with it. A constant’s value cannot be changed throughout the execution of a PHP script, as its name implies.
The define() method is used to create a constant. The first argument to the define() function is the name of the constant, and the second argument is the value of the constant. Consider the following example:
<?php define('WIDTH','1140px'); echo WIDTH;
Constant names are always written in uppercase. Unlike variables, the name of a constant does not begin with the dollar symbol ($).
Constant names are case-sensitive by default. It signifies that Breadth and width are not the same thing.
A constant in PHP 5 can hold a simple value such as a number, a string, or a boolean value. A constant can now hold an array since PHP 7.0. Consider the following scenario:
<?php define( 'ORIGIN', [0, 0] );
Constants, like superglobal variables, can be accessed from anywhere in the script.
The const keyword in PHP gives you another way to specify a constant. The syntax is as follows:
const CONSTANT_NAME = value;
The constant name is defined following the const keyword in this syntax. You use the assignment operator (=) and the constant value to assign a value to a constant. A number, a string, or an array can be used as a scalar constant value.
The SALES TAX constant is defined in the following example with the const keyword:
<?php const SALES_TAX = 0.085; $gross_price = 100; $net_price = $gross_price * (1 + SALES_TAX); echo $net_price; // 108.5
The const keyword is used in the following example to define an RGB constant that holds an array:
<?php const RGB = ['red', 'green', 'blue'];
The define() function is a function, but the const language construct is a language construct.
The define() function declares a constant at runtime, whereas the const keyword declares a constant at compile time.
To put it another way, you can conditionally define a constant using the define() method, as shown below:
<?php if(condition) { define('WIDTH', '1140px'); }
The const keyword, on the other hand, cannot be used to define a constant in this manner. The syntax of the following code, for example, is incorrect:
<?php if(condition) { const WIDTH = '1140px'; }
Second, you can use the define() method to create a constant with a name that is derived from an expression. For example, the following defines three constants with the values 1, 2, and 3: OPTION 1, OPTION 2, and OPTION 3.
<?php define('PREFIX', 'OPTION'); define(PREFIX . '_1', 1); define(PREFIX . '_2', 2); define(PREFIX . '_3', 3);
The const keyword, on the other hand, cannot be used to specify a constant name derived from an expression.
You can use the const keyword to define constants to make the code more obvious unless you wish to specify a constant conditionally or with an expression.