What are PHP Constant variables and How to define them?

What is a constant?

A PHP constant is a type of variable whose value cannot be changed or undefined once defined.

1. How to define a PHP variable?

A PHP variable starts with the $ sign, followed by the name of the variable, like – $test, $name, $age, etc.

<?php
$name = "John";
echo $name;
John

1.1. The value of a variable can be changed in PHP

After defining a variable, you can change the value of a variable in PHP.

<?php
$name = "John";

// Changing the value
$name = "Mark";

echo $name;
Mark

1.2. PHP variable naming conventions

You have to follow some naming conventions or rules in order to create a PHP variable.

  1. PHP variables always start with the $ sign.
  2. A variable name must start with a letter or the underscore. Like – $test or $_name.
  3. A variable name can only contain alpha-numeric characters and underscores. (az, AZ, 09, _)
  4. You cannot start a variable name with a number. $5test ❌ | $test5 ✔️
  5. Variable names are case-sensitive. Therefore, the $name and $Name are not the same.

2. How to define a PHP Constant?

The define() function is used to create a constant in PHP.

This define() function has two parameters –

define("name", value,)
  • “name” => The name of the constant. A constant name begins with a letter or underscore without the $ sign.
  • value => Value for the constant.
  • Constant names are also case-sensitive like variables.
<?php
define("NAME", "John");
echo NAME;
John

2.1. A constant cannot be re-declared

You cannot re-declare a constant, if you do so, it will give you an error.

<?php
define("NAME", "Mark");
define("NAME", "John");

echo  NAME;
PHP Warning:  Constant "NAME" already defined

Always check whether the constant is defined before defining a constant.

The defined(“name”) function returns true if the given constant is defined.

<?php
define("NAME", "Mark");

var_dump(defined("NAME"));
var_dump(defined("AGE"));
bool(true)
bool(false)

2.2. Best way to define a PHP constant

<?php
define("NAME", "Mark");

if(!defined("NAME")) define("NAME", "John");

//Shortcut
defined("AGE") or define("AGE",22);

echo NAME." => ".AGE;
Mark => 22

2.3. Constants are like Super-Global variables

PHP constants are like superglobal variables. Therefore, you can access constants from anywhere in a script without regard to scope.

<?php
// Variable Example
$name = "John";

function test(){
    echo $name;
}

test();
PHP Warning: Undefined variable "$name"
<?php
// Constant Example
defined("NAME") || define("NAME", "John");

function test(){
    echo NAME;
}

test();
John

3. When to use which (Variable or Constant)?

We usually use variables to build programs, but if the value of one variable is fixed and you want to use the variable across the entire script, in that case, you can use constants.