PHP Constants

What is a Constant in PHP

A constant in PHP is a name or identifier for a fixed value. Constants are similar to variables, but once defined, they cannot be undefined or changed (except for magic constants).

Constants are particularly useful for storing data that remains constant throughout the execution of a script, such as configuration settings like database credentials, website base URLs, company names, etc.

To define constants in PHP, you use the define() function, which takes two arguments: the name of the constant and its value. Once defined, the constant's value can be accessed at any point in the script by referencing its name. Here's a simple example:

<?php
// Defining constant
define("SITE_URL", "https://www.codinghub360.com/");

// Using constant
echo 'Thank you for visiting - ' . SITE_URL;
?>

The output of the above code will be:

Thank you for visiting - https://www.codinghub360.com/

The PHP echo statement is commonly used to display or output data to the web browser. We will explore more about this statement in the upcoming chapter.

Tip: By storing a value in a constant instead of a variable, you can ensure that the value won't be accidentally changed while your application is running.


Naming Conventions for PHP Constants

The names of constants must adhere to the same rules as variable names. This means a valid constant name must start with a letter or underscore, followed by any number of letters, numbers, or underscores. One key distinction: constant names do not require the $ prefix.

Note: By convention, constant names are typically written in uppercase letters. This practice aids in easily identifying and distinguishing constants from variables within the source code.