PHP Constants (original) (raw)

Last Updated : 11 Apr, 2025

A constant is a name or identifier used to store a fixed value that does not change during the execution of a PHP script. Unlike variables, constants do not start with a $ symbol and stay the same once they are defined.

**Creating a Constant in PHP

There are two ways to create constants in PHP:

1. Using define() Function

The define() function in PHP is used to create a constant, as shown below:

**Syntax

define( name, value);

The parameters are as follows:

**Now, let us understand with the help of the example:

PHP `

`

Output

GeeksforGeeks GeeksforGeeks

2. Using the Const Keyword

The const keyword is another way to define constants but is typically used inside classes and functions. The key difference from define() is that constants defined using const cannot be case-insensitive.

**Syntax

const CONSTANT_NAME = value;

**Now, let us understand with the help of the example:

PHP `

`

define() vs const

define() const
Used to create constants using a function. Used to create constants using a keyword.
Works at runtime. Works at compile time.
Slightly older and more flexible. Preferred in modern PHP code for structure and readability.

**Constants are Global

By default, constants are **global and can be used throughout the script, accessible inside and outside of any function.

**Now, let us understand with the help of the example:

PHP `

`

Output

GeeksforGeeks GeeksforGeeks

Predefined Constants in PHP

PHP provides many built-in constants, such as:

Best Practices for Using Constants

Constants vs Variables

Both are used to store values in PHP. Constants hold fixed values that never change, whereas variables can be updated as the script runs. Below is the difference between them:

Constant Variable
Used to store values that do not change during script execution. Used to store values that can change while the script runs.
Defined once and cannot be redefined. Can be updated or reassigned multiple times.
Do not start with a $ symbol. Always start with a $ symbol.
Value stays the same everywhere in the program. Value can be different in different parts of the program.

Conclusion

Constants in PHP are essential for storing fixed values that remain the same throughout the execution of a script. They help make your code more readable, maintainable, and error-free by preventing accidental value changes. By using constants wisely, especially for configuration settings, limits, and fixed labels—you can write cleaner and more reliable PHP programs. Understanding the difference between constants and variables also ensures you choose the right one based on the behavior your code requires.