Constants in PHP

Learn via video courses
Topics Covered

In PHP, constants are identifiers for values that cannot be altered during script execution, unlike variables. Defined using the define() function or the const keyword, they are immutable and remain constant throughout the program. Typically uppercase, constants' names start with a letter or underscore, followed by any combination of letters, numbers, or underscores without special characters. Essential for storing values like configuration settings and mathematical constants, they ensure code consistency and prevent accidental modifications, enhancing reliability and readability in PHP programming.

Transform Your Career

Choose from our industry-leading programs designed for career success

NSDC Certified

Modern Software and AI Engineering Program

Master full-stack development with AI integration

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Modern Data Science and ML with specialisation in AI

Advanced data science techniques with AI specialization

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

Advanced AIML with Specialisation in Agentic AI

Deep dive into AIML with focus on Agentic systems

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

DevOps, Cloud & AI Platform Engineering

Build and manage AI-powered cloud infrastructure

12 MonthsDuration
AI-LedCurriculum
Career SupportSupport
GoogleAmazonPaytm+1000 more
Go to Program
NSDC Certified

AI Engineering Advanced Certification by IIT-Roorkee

Premier AI engineering certification from IIT-Roorkee

3 MonthsDuration
AI-LedCurriculum
Career SupportSupport
Program highlights
Go to Program

Create a PHP Constant

To create a constant in PHP, you can use either the define() function or the const keyword. Here's an example of creating a constant using both methods:

Using define() function:

Using const keyword:

Explanation

In both cases, we define a constant named GREETING with the value 'Hello, World!'. Constants in PHP follow certain naming conventions, typically using uppercase letters with underscores for multiple words (e.g., CONSTANT_NAME).

Once defined, constants can be accessed anywhere in the script by using their name without the need for a leading dollar sign ($). Constants cannot be redefined or modified once defined, making them suitable for storing fixed values that should remain constant throughout the execution of the script. Run the above code in your editor for a better and clear explanation.

Examples

Let us see a few examples of using the constant in php.

Create an Array constant using the define() function

Output

Explanation

In this example, we create a constant named CONFIG using the define() function. The constant is assigned an associative array that represents database configuration settings.

The array consists of key-value pairs, where the keys represent the configuration setting names (e.g., 'DB_HOST', 'DB_USER'), and the values hold the corresponding values for each setting ('localhost', 'username', 'password', 'database').

The print_r() function is then used to display the contents of the CONFIG constant. It will output the associative array with its keys and values, providing a visual representation of the database configuration settings. Run the above code in your editor for a better and clear explanation.

Constants are automatically global

Explanation

In this example, we define a constant named GREETING with the value 'Hello, World!'. Inside the printGreeting() function, we simply echo the value of the GREETING constant.

When we call the printGreeting() function, it successfully accesses and displays the value of the GREETING constant, which is 'Hello, World!'. This demonstrates that constants are automatically accessible in the function scope, even though they are defined outside of the function. Run the above code in your editor for a better and clear explanation.

Free Courses by top Scaler instructors
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course
Python Course for Beginners With Certification: Mastering the Essentials
Java Course - Mastering the Fundamentals
DBMS Course - Master the Fundamentals and Advanced Concepts
JavaScript Course With Certification: Unlocking the Power of JavaScript
C++ Course: Learn the Essentials
Python and SQL for Data Science Course

Constant vs Variables

Constants and variables in PHP are used to store and manage data, but they have several key differences. Here's a comparison between constants and variables in PHP let us see below:

Declaration and Assignment:

  • Constants: Constants are declared using the define() function or the const keyword and must be assigned a value at the time of declaration. Once defined, their value cannot be changed during the script's execution.
  • Variables: Variables are declared using the $ symbol followed by a name and can be assigned values using the assignment operator (=). The value of a variable can be changed or updated multiple times during the script's execution.

Scope:

  • Constants: Constants are automatically global, meaning they can be accessed from anywhere within the script without any special keywords or syntax.
  • Variables: Variables have different scopes depending on where they are declared. They can have global scope (accessible throughout the script) or local scope (limited to a specific function or code block). Mutability:
  • Constants: Constants are immutable, meaning their value cannot be modified once defined. They are ideal for storing values that should remain constant throughout the execution of the script.
  • Variables: Variables are mutable, allowing their value to be changed or reassigned at any point during the script's execution.

Usage and Purpose:

  • Constants: Constants are typically used to store fixed values that should not be modified, such as configuration settings, mathematical values, or system-related information. They provide a convenient way to manage global values throughout the codebase.
  • Variables: Variables are used to store and manipulate data that can change during the execution of a script. They are essential for storing user input, intermediate calculation results, or dynamically changing values.

Scaler Placement Report and Statistics

₹23L
AVG CTC
SCALER PLACEMENT PROOF

Scaler learners achieved 2.5x salary growth with average post-Scaler CTC reaching ₹23L.

11,000+placements
650+companies
Verified data
Hiring Partners:
GoogleGoogleAmazonAmazonMicrosoftMicrosoftFlipkartFlipkartAdobeAdobe1200+ more

Conclusion

  • Constants are used to store values that remain constant and cannot be modified during the execution of a script.
  • Constants are automatically global and can be accessed from anywhere within the script without the need for any special keywords or syntax.
  • Constants follow naming conventions in PHP, typically using uppercase letters with underscores for multiple words, making them easily distinguishable from variables.
  • Constants are commonly used for storing configuration settings, such as database credentials or application-specific values, providing a centralized and consistent approach to managing these settings.
  • Constants enhance code readability by using meaningful names for important values, making the code easier to understand and maintain. They also promote code consistency by ensuring that values are consistently used throughout the codebase.
  • Constants are determined at compile-time, making them available and ready to use as soon as the script starts running.