PHP Constants
A constant is an identifier (name) for a simple value that cannot be changed during script execution. Unlike variables, constants do not use the $ prefix and are global by default.
Defining Constants with define()
The define() function creates a constant at runtime. It accepts the name, value, and an optional case-insensitive flag (deprecated in PHP 8).
<?php
define("SITE_NAME", "Tutorials Logic");
define("MAX_USERS", 1000);
define("PI", 3.14159);
echo SITE_NAME; // Tutorials Logic
echo MAX_USERS; // 1000
echo PI; // 3.14159
// Constants are global — accessible inside functions too
function showSite() {
echo SITE_NAME; // works without global keyword
}
showSite();
?>
Defining Constants with const
The const keyword defines constants at compile time. It can be used inside classes and is preferred for class-level constants.
<?php
const APP_VERSION = "2.5.0";
const DEBUG_MODE = false;
echo APP_VERSION; // 2.5.0
// Inside a class
class Config {
const DB_HOST = "localhost";
const DB_PORT = 3306;
}
echo Config::DB_HOST; // localhost
echo Config::DB_PORT; // 3306
// Retrieve constant value dynamically
$name = "APP_VERSION";
echo constant($name); // 2.5.0
?>
Predefined Constants
PHP ships with many built-in constants you can use anywhere in your scripts.
<?php
echo PHP_VERSION; // e.g. 8.2.0
echo PHP_INT_MAX; // 9223372036854775807
echo PHP_INT_MIN; // -9223372036854775808
echo PHP_FLOAT_MAX; // 1.7976931348623E+308
echo PHP_EOL; // newline character (\n on Linux)
echo PHP_MAJOR_VERSION; // e.g. 8
echo DIRECTORY_SEPARATOR; // / on Linux, \ on Windows
// Magic constants (change based on where they are used)
echo __FILE__; // full path to current file
echo __DIR__; // directory of current file
echo __LINE__; // current line number
echo __FUNCTION__; // current function name (inside a function)
echo __CLASS__; // current class name (inside a class)
?>
Magic Constants in Context
Magic constants are special constants whose values change depending on where they are used.
<?php
function greet() {
echo "Function: " . __FUNCTION__; // greet
}
greet();
class Animal {
public function speak() {
echo "Class: " . __CLASS__; // Animal
echo "Method: " . __METHOD__; // Animal::speak
}
}
$a = new Animal();
$a->speak();
// Namespace magic constant
namespace MyApp;
echo __NAMESPACE__; // MyApp
?>
Ready to Level Up Your Skills?
Explore 500+ free tutorials across 20+ languages and frameworks.