ADVERTISEMENTS

PHP Constants

In PHP, a constant is a name or identifier that is assigned a fixed value that cannot be changed during the execution of the script. Constants are useful when you need to define values that should not be changed throughout the execution of your program, such as configuration values or mathematical constants. There are two ways to define a constant:

  • using the define() function
  • using the const keyword.

define() method

You can define a constant using the define() function. The define() function takes two arguments: the name of the constant and its value. Here's the syntax:

define(name, value, case_insensitive);
  • name : The name of the constant. This is a string and should be written in all uppercase letters by convention.
  • value : The value of the constant. This can be any valid PHP expression.
  • case_insensitive (optional) : A boolean value that determines whether the constant name should be case-insensitive. If set to true, the constant name will be case-insensitive. If not specified or set to false, the constant name will be case-sensitive.
define("MY_CONSTANT", "Hello, world!");
echo MY_CONSTANT; // Output: Hello, world!

In this example, we define a constant called MY_CONSTANT with a value of "Hello, world!" using the define() function. We then print the value of the MY_CONSTANT constant to the screen using echo.

Once a constant is defined, its value cannot be changed. Attempting to change the value of a constant will result in a warning. To check if a constant is defined, you can use the defined() function.

ADVERTISEMENTS

const keyword

You can also define a constant using the const keyword. The const keyword is used to define class constants or global constants within a namespace. Here's the syntax:

const name = value;
  • name : The name of the constant. This is a string and should be written in all uppercase letters by convention.
  • value : The value of the constant. This can be any valid PHP expression.
const MY_CONSTANT = "Hello, world!";
echo MY_CONSTANT; // Output: Hello, world!

In this example, we define a constant called MY_CONSTANT with a value of "Hello, world!" using the const keyword. We then print the value of the MY_CONSTANT constant to the screen using echo.

Once a constant is defined using the const keyword, its value cannot be changed. Attempting to change the value of a constant will result in a fatal error. Note that unlike the define() function, the const keyword cannot be used to define constants outside of classes or namespaces.

ADVERTISEMENTS