PHP constants vs variables

The differences between constants and variables in PHP isn’t enormous but here they are:

A constant cannot be changed once set and constants are global so unlike variables they can be accessed in functions without being passed in.

This behaviour makes constants favourable for config like values i.e API keys, MySQL connection details and other config/options that do not get changed.

Code can also be more understandable with using constants and variables instead of just only variables.

Setting a constant is done with define(), calling the constant does not need the $ before the name:

define("API_KEY", "VTb91foKYo");

echo API_KEY;//VTb91foKYo


const API_KEY = "VTb91foKYo";

Note that using const means the constant is case sensitive.

define() may be case insensitive depending if the parameter is passed through.

Constant being a global example:

function testFunction()
    return "" . API_KEY . "";

echo testFunction();//

A constant can also be an array:

define('DB_DETAILS', array(
    'host' => '',
    'database' => 'table_name',
    'username' => 'gary',
    'password' => 'DxQvYmhcUo'

echo DB_DETAILS['username'];//gary

Checking if a constant is defined with the defined() function:

if (defined('API_KEY')) {
    echo API_KEY;