← Back to PHP Course | Chapter 1: Introduction & Basics | Lesson 11 of 13

PHP Constants

Defining Constants with define()

define(SITE_NAME, 'Cookies & Cursor') creates a constant at runtime. Once set, a constant's value is locked for the rest of the script's execution — there's no reassignment operator for constants the way there is for variables, which is exactly the guarantee you want for values that must never change mid-script.

Example: Defining Constants with define()

php
<?php
define('SITE_NAME', 'Cookies & Cursor');
echo SITE_NAME;
?>

The const Keyword

The const keyword defines a constant at compile time rather than runtime, which makes it slightly faster and is the standard way to declare constants inside a class. Outside a class, define() and const both work, but const requires the value to be a fixed literal rather than the result of a function call.

Example: The const Keyword

php
<?php
const MAX_USERS = 100;
echo MAX_USERS;
?>

Constant Scope

Unlike a variable, a constant is automatically accessible everywhere in the script the moment it's defined — inside every function and every included file — without needing the global keyword. That global-by-default behavior is exactly why constants suit values like configuration settings or fixed limits.

Example: Constant Scope

php
<?php
define('APP_VERSION', '1.0');

function showVersion() {
    echo APP_VERSION;
}
showVersion();
?>

Magic Constants

PHP predefines several 'magic constants' — like __LINE__ and __FILE__ — whose value changes depending on where in your code they appear. __LINE__ always evaluates to the current line number, and __FILE__ to the full path of the file it's written in, which makes both genuinely useful for logging and debugging.

Example: Magic Constants

php
<?php
echo "Line: " . __LINE__ . "\n";
echo "File: " . __FILE__;
?>

Constant Best Practices

Writing constant names in ALL_CAPS isn't enforced by PHP, but it's a near-universal convention that lets a reader instantly tell MAX_RETRIES is a fixed constant rather than a variable that might change. Grouping related constants together near the top of a file also makes configuration easy to find later.

Example: Constant Best Practices

php
<?php
define('MAX_RETRIES', 3);
define('MIN_RETRIES', 1);
echo MAX_RETRIES;
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.