Web Analytics

PHP Constants

Beginner~20 min read

Constants are like variables that never change. Once defined, their value remains the same throughout your program. They're perfect for configuration values, API keys, and other fixed data!

What Are Constants?

A constant is an identifier for a simple value that cannot be changed during script execution. Unlike variables:

  • Constants do NOT start with $
  • Constants are automatically global
  • Constants cannot be redefined or undefined
  • Constants can only hold scalar values (not arrays or objects in PHP < 5.6)
Output
Click Run to execute your code

Defining Constants: define()

The define() function creates a constant at runtime:

<?php
// Syntax: define(name, value, case_insensitive)
define("SITE_NAME", "8gwifi.org");
define("MAX_USERS", 100);
define("PI", 3.14159);
define("DEBUG_MODE", true);

echo SITE_NAME;  // Output: 8gwifi.org
echo MAX_USERS;  // Output: 100
?>
Naming Convention: By convention, constant names are written in UPPERCASE with underscores separating words (UPPER_SNAKE_CASE).

Case-Insensitive Constants (Deprecated)

<?php
// Third parameter makes it case-insensitive (deprecated in PHP 7.3)
define("GREETING", "Hello", true);

echo GREETING;  // Works
echo greeting;  // Also works (but deprecated!)
?>
Deprecated: Case-insensitive constants are deprecated as of PHP 7.3 and removed in PHP 8.0. Always use case-sensitive constants!

Defining Constants: const Keyword

The const keyword defines constants at compile time (PHP 5.3+):

<?php
const APP_VERSION = "1.0.0";
const MAX_LOGIN_ATTEMPTS = 3;
const ENABLE_CACHE = true;

echo APP_VERSION;  // Output: 1.0.0
?>

define() vs const

Feature define() const
When defined Runtime Compile time
Inside conditionals โœ… Yes โŒ No
Expression values โœ… Yes โŒ No (PHP < 5.6)
Namespace support โŒ No โœ… Yes
Class constants โŒ No โœ… Yes
Arrays (PHP 7+) โœ… Yes โœ… Yes
<?php
// define() can be conditional
if ($production) {
    define("DEBUG", false);
} else {
    define("DEBUG", true);
}

// const cannot be conditional
const DEBUG = false;  // โœ… Works at top level
if ($production) {
    const DEBUG = false;  // โŒ Syntax error!
}
?>

Array Constants (PHP 5.6+)

Since PHP 5.6, constants can hold arrays:

<?php
const COLORS = ["red", "green", "blue"];
define("SIZES", ["small", "medium", "large"]);

echo COLORS[0];  // Output: red
echo SIZES[1];   // Output: medium
?>

Checking if Constant Exists

Use defined() to check if a constant is defined:

<?php
if (defined("DEBUG_MODE")) {
    echo "Debug mode is defined";
}

// Get constant value safely
$debug = defined("DEBUG_MODE") ? DEBUG_MODE : false;
?>

Magic Constants

PHP provides special "magic constants" that change depending on where they're used:

Constant Description Example Value
__LINE__ Current line number 42
__FILE__ Full path and filename /path/to/file.php
__DIR__ Directory of the file /path/to
__FUNCTION__ Function name myFunction
__CLASS__ Class name MyClass
__METHOD__ Class method name MyClass::myMethod
__NAMESPACE__ Current namespace App\Controllers
__TRAIT__ Trait name MyTrait
<?php
echo "Current file: " . __FILE__;
echo "Current directory: " . __DIR__;
echo "Current line: " . __LINE__;

function myFunction() {
    echo "Function: " . __FUNCTION__;
}

class MyClass {
    public function myMethod() {
        echo "Class: " . __CLASS__;
        echo "Method: " . __METHOD__;
    }
}
?>
Pro Tip: __DIR__ is extremely useful for including files with absolute paths, making your code more portable!

Predefined Constants

PHP has many built-in constants:

Constant Description Example
PHP_VERSION PHP version string "8.2.0"
PHP_OS Operating system "Linux"
PHP_INT_MAX Largest integer 9223372036854775807
PHP_FLOAT_MAX Largest float 1.7976931348623E+308
true Boolean true true
false Boolean false false
null Null value null
<?php
echo PHP_VERSION;  // Current PHP version
echo PHP_OS;       // Operating system
echo PHP_INT_MAX;  // Maximum integer value
?>

Class Constants

Constants can be defined inside classes:

<?php
class Database {
    const HOST = "localhost";
    const PORT = 3306;
    const NAME = "mydb";
    
    public function connect() {
        echo "Connecting to " . self::HOST;
    }
}

echo Database::HOST;  // Access from outside
?>

Best Practices

When to Use Constants:
  • Configuration values (database credentials, API keys)
  • Fixed mathematical values (PI, E)
  • Application settings (version, environment)
  • Status codes or flags
  • File paths
Best Practices:
  • Use UPPER_SNAKE_CASE for constant names
  • Prefer const for simple values
  • Use define() for conditional constants
  • Group related constants in classes
  • Document what each constant represents

Common Mistakes

1. Using $ with constants

<?php
define("MAX_SIZE", 100);

echo $MAX_SIZE;  // โŒ Undefined variable
echo MAX_SIZE;   // โœ… Correct
?>

2. Trying to change a constant

<?php
define("VERSION", "1.0");
define("VERSION", "2.0");  // โŒ Warning: already defined

VERSION = "2.0";  // โŒ Parse error
?>

3. Using const in conditional

<?php
if ($debug) {
    const DEBUG = true;  // โŒ Syntax error!
}

// Use define() instead
if ($debug) {
    define("DEBUG", true);  // โœ… Correct
}
?>

Exercise: Configuration Constants

Task: Create a configuration system using constants!

Requirements:

  • Define constants for: app name, version, environment
  • Create database connection constants
  • Use magic constants to show file info
  • Check if constants are defined before using
Show Solution
<?php
// Application constants
const APP_NAME = "MyApp";
const APP_VERSION = "1.0.0";
const ENVIRONMENT = "development";

// Database constants
define("DB_HOST", "localhost");
define("DB_NAME", "myapp_db");
define("DB_USER", "root");
define("DB_PASS", "");

// Display configuration
echo "Application: " . APP_NAME . " v" . APP_VERSION . "\n";
echo "Environment: " . ENVIRONMENT . "\n";
echo "Config file: " . __FILE__ . "\n";

// Safe constant access
if (defined("DB_HOST")) {
    echo "Database: " . DB_HOST . "/" . DB_NAME;
}
?>

Summary

  • Constants: Values that never change
  • No $: Constants don't use dollar sign
  • define(): Runtime definition, conditional use
  • const: Compile-time definition, class support
  • Global: Automatically available everywhere
  • Magic: __FILE__, __DIR__, __LINE__, etc.
  • defined(): Check if constant exists
  • Naming: Use UPPER_SNAKE_CASE

What's Next?

Congratulations! You've completed Module 2 and mastered variables, data types, type juggling, strings, and constants. In the next module, we'll dive into Operators - the symbols that let you perform calculations, comparisons, and logical operations!