Constants in PHP: How They Work & Examples

Constants in PHP

Constants in PHP store fixed values that don’t change during execution. We will cover the following topics in this article:

  • What constants are in PHP? and how do they work?
  • How constants work across different scopes.
  • The difference between constants and variables in PHP
  • How to check constants.
  • How to access constants in PHP classes.

Let’s start with the main definition and syntax.

What Are Constants?

Constants store fixed values that do not change during script execution. In PHP, you define constants with define() or const. Constants do not start with a dollar sign ($) and remain globally accessible once declared.

Constants defined by define() are case-sensitive by default, but you can make them case-insensitive with a third parameter (define("CONNAME", "value", true)).

Hence, case-insensitive constants are deprecated in PHP 7.3 and later. The const keyword always creates case-sensitive constants.

Here is an example of two both const and define():

define("SITE_NAME", "FlatCoding.com");  
echo SITE_NAME; 


const MAX_MEMBERS = 100;  
echo MAX_MEMBERS;

So, here are the key differences:

  • define() works at runtime and allows dynamic names.
  • const works at compile time and must use a fixed name.

Constants cannot be re-assigned once they are defined. Its value is fixed and cannot be changed during the script execution. If you attempt to reset or redefine a constant will give you an error.

For example:

define("SITE_NAME", "FlatCoding Tutorials");
echo SITE_NAME;  

define("SITE_NAME", "FlatCoding New Tutorials"); // => error

Here is the output:

FlatCoding Tutorials
PHP Warning: Constant SITE_NAME already defined in /constants.php on line 4

The same rule applies to constants declared with const.

But, how do constants work across different scopes?

Constants are always global in where they are defined. You can access them inside and outside functions. That doesn’t need the global keyword.

While the class constants (const NAME = value;) belong to a specific class and require the ClassName::CONSTANT syntax for access.

Here are quick instructions to show you how to name constants in PHP:

  • Use uppercase letters with underscores to separate words (e.g., MAX_USERS, DB_HOST_NAME).
  • Make constants easy to recognize for better readability.
  • Choose meaningful names that clearly describe their purpose.
  • Avoid generic names like VALUE or NUMBER to prevent confusion.

Let’s move on to the following section to understand how it works in classes.

Class Constants in PHP with the “const” Keyword

You can define constants inside a class with the const keyword. These constants belong to the class and cannot be changed once set. The class constants must have a fixed name and value if you don’t need to use regular constants.

Here is an example:

class Config {  
    const SITE_NAME = "FlatCoding";  
    const MAX_USERS = 100;  
}  

So, how do you access constants within classes in PHP?

You access class constants with the :: scope resolution operator. You do not use the $ sign-like variables.

Here is an example of how to access the class constants.

echo Config::SITE_NAME;  
echo Config::MAX_USERS;  

Here is the output:

FlatCoding
100

You can use self::CONSTANT_NAME inside the class if you need to access it within the same class.

class Config {  
    const SITE_NAME = "FlatCoding";  

    public function getSiteName() {  
        return self::SITE_NAME;  
    }  
}  

$config = new Config();  
echo $config->getSiteName();

Output:

FlatCoding

Use parent::CONSTANT_NAME to access constants from a parent class:

class BaClass {  
    const MESSAGE = "Welcome to FlatCoding programming tutorials.";  
}  

class ChildClass extends BaClass{  
    public function showMessage() {  
        return parent::MESSAGE;  
    }  
}  

$child = new ChildClass();  
echo $child->showMessage(); 

Output:

Welcome to FlatCoding programming tutorials.

Class constants are useful for fixed values like configuration settings or role permissions.

In the following section, you will understand how to check constants.

Check if a Constant Exists Using defined() Keyword in PHP

You can check if a constant exists with the defined() function that before use it. This prevents errors when accessing undefined constants.

Here is the syntax:

defined("CONSTANT_NAME");

It returns true if the constant is defined and false if it is not.

For example:

define("SITE_NAME", "FlatCoding");  

if (defined("SITE_NAME")) {  
    echo "SITE_NAME is defined.";  
} else {  
    echo "SITE_NAME is not defined.";  
}  

The output:

FlatCoding is defined.

Use defined() with the ClassName::CONSTANT_NAME format to check if a class constant exists:

class Config {  
    const MAX_USERS = 100;  
}  

if (defined("Config::MAX_USERS")) {  
    echo "MAX_USERS is defined.";  
} else {  
    echo "MAX_USERS is not defined.";  
}  

Output:

MAX_USERS is defined.

In the following section, you will understand the difference between “const” and “define()”.

The Difference Between “const” and “define()” in PHP Constants

Use const for class constants and fixed values. Use define() it when you need runtime evaluation or when defining constants inside functions.

Here are the key differences:

Featureconstdefine()
Syntaxconst NAME = value;define("NAME", value);
ScopeGlobal, classGlobal only
Evaluated AtCompile timeRuntime
Works in Classes
Works in Functions
Supports Arrays
Case SensitivityAlways case-sensitiveCase-sensitive (older versions allowed case-insensitive)

Let’s move on to the following section to see an example of a dynamic array.

Constants in PHP with Arrays

You can define an array constant with define(), which supports dynamic values and works at runtime.

define("COLORS", ["Red", "Green", "Blue"]);  

echo COLORS[0]; // Output: Red

While the const keyword also supports arrays, but the values must be known at compile time.

const FRUITS = ["Apple", "Banana", "Cherry"];  

echo FRUITS[1]; // Output: Banana  

But you cannot reassign the array once you assign it to a constant. If you try, it will show an error.

Wrapping Up

You learned in this tutorial how constants in PHP store fixed values that do not change within execution. We also covered several important topics, such as:

  • How to define constants and their behavior across different scopes
  • The key differences between constants and variables.

Here is a quick recap:

  • Constants store values that remain the same throughout script execution. They can be defined using define() or const.
  • Constants are globally accessible, but class constants must be accessed with the ClassName::CONSTANT syntax.
  • They cannot be reassigned once set, while variables can change during execution.
  • Use the defined() function to check if a constant exists.
  • Use the :: scope resolution operator to access constants within classes.
  • You need to use const for compile-time constants (typically in classes) and define() for runtime constants (typically in global scope or functions).

FAQ’s

What is a constant in PHP?

A constant in PHP is a fixed value that does not change during script execution. You define constants using define() or const. If you don't need use variables, constants do not start with a $ sign and are globally accessible once declared.

What is the difference between const and define() in PHP?

  • const is used for compile-time constants, mainly inside classes.
  • define() works at runtime and allows dynamic names.
  • const is always case-sensitive, while define() was case-insensitive in older PHP versions.
  • define() can be used inside functions, whereas const cannot.

Can we change the value of a constant in PHP?

No, once a constant is defined, you cannot reassign or modify its value. Trying to do so will result in an error.

How do you check if a constant is defined in PHP?

Use the defined("CONSTANT_NAME") function. It returns true if the constant exists and false if it does not.

How do you access constants in a PHP class?

Use the ClassName::CONSTANT_NAME syntax. Inside the class, use self::CONSTANT_NAME and for parent class constants, use parent::CONSTANT_NAME.

Can constants store arrays in PHP?

Yes, both define() and const can store arrays, but const requires values to be known at compile time.

Are PHP constants global?

Yes, constants are always global, meaning they can be accessed anywhere in the script without using the global keyword. However, class constants belong to a specific class.
Next Article

PHP OOP Programming: A Complete Tutorial

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.