PHP Constants

What is a Constant?

A constant is an identifier (name) for a value that cannot be changed during the script's execution. Constants do not start with a $ and are case-sensitive by default.

Using define()

define() is a function used to create constants:

define("SITE_NAME", "MySite");
echo SITE_NAME;
  • First argument is the name (as a string)
  • Second is the value
  • OPTIONAL third argument (true/false) to make it case-insensitive

Using const

const is used to define constants in the global scope or inside classes:

const PI = 3.14159;
echo PI;

Inside a class:

class Math {
  const VERSION = "1.0";
}

echo Math::VERSION;

Constants Are Global

You can access a constant from anywhere in the script, even inside functions:

define("APP_NAME", "PHP Demo");

function showApp() {
  echo APP_NAME;
}

Predefined Constants

PHP provides many built-in constants:

  • PHP_VERSION — current PHP version
  • PHP_OS — operating system PHP is running on
  • PHP_INT_MAX — largest integer supported
  • __LINE__, __FILE__, __DIR__ — magic constants
echo __FILE__;
echo PHP_VERSION;

Constant vs Variable

  • Constants don't use $
  • Constants can't be reassigned
  • Constants are automatically global

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic