Skip to content

PHP Tutorial Variables and Constants

The define() Function

Lesson 27 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

define() creates a constant, like const, but it is an ordinary function call. That means it runs while the script is running, so you can use it inside an if or give it a name that is built from a string.

index.php
PHP
<?php
define("SITE_NAME", "Code Corner");

echo SITE_NAME;
Output
OUTPUT
Code Corner

When define() is the right tool

index.php
PHP
<?php
$environment = "local";

if ($environment === "local") {
    define("DEBUG", true);
} else {
    define("DEBUG", false);
}

echo DEBUG ? "Debug is on" : "Debug is off";
Output
OUTPUT
Debug is on

const cannot be written inside an if, but define() can.

Check if a constant exists

Use defined() to ask, and constant() to read a constant whose name is in a string.

index.php
PHP
<?php
define("VERSION", "1.2");

var_dump(defined("VERSION"));
var_dump(defined("MISSING"));

$name = "VERSION";
echo constant($name);
Output
OUTPUT
bool(true)
bool(false)
1.2

const vs define()

constdefine()
Inside a classYesNo
Inside if or loopsNoYes
Name can be computedNoYes
Value can be computed with functionsNoYes
Style in modern codePreferredOnly when needed

Defining a constant twice

PHP will not replace a constant. A second define() with the same name gives a warning, and the first value stays.

index.php
PHP
<?php
define("MODE", "first");
define("MODE", "second");

echo MODE;
Output
OUTPUT
Warning: Constant MODE already defined in /path/to/index.php on line 3
first
info
Configuration files often use define()
Old code and WordPress’s wp-config.php use define() for settings. Now you know what those lines mean.