Constant in PHP

Constants are like variables except that once they are defined they cannot be changed or undefined.

A valid constant name starts with a letter or underscore (no $ sign before the constant name).

Unlike variables, constants are automatically global across the entire script.

Additionally, meaningful and descriptive names should be used for all identifiers to improve code readability and maintainability.

Using consistent naming conventions, such as camelCase for variables and functions and StudlyCase for classes, can make your code more organized and easier to understand.

To create a constant, use the define() function.

define(name, value, case-insensitive)
  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false

The examples below creates constants with a case-sensitive name:

<?php
	define("GREETING", "Welcome to my Website!", true);  
	echo GREETING;
?>

Define constant using cons keyword in PHP The const keyword defines constants at compile time. It is a language construct not a function. It is bit faster than define(). It is always case sensitive.

Example

<?php
	const MSG="Hello world!";
	echo MSG;
?>