search
php

Fix: Undefined constant error PHP fix

Quick fix for 'Undefined constant' error in PHP. Learn how to properly define and use constants in PHP applications.

person By Gautam Sharma
calendar_today January 8, 2026
schedule 2 min read
PHP Constants Error Fix Configuration Debugging

The ‘Undefined constant’ error occurs when PHP encounters a constant that hasn’t been defined, often due to typos, missing definitions, or scope issues.


How the Error Happens

❌ Error Scenario:

<?php
// ❌ This causes the error
echo API_URL; // Fatal error: Uncaught Error: Undefined constant "API_URL"
?>

✅ Quick Fix - Define and Use Constants Properly

Solution 1: Define Constants Before Use

<?php
// ✅ Define constant before using it
define('API_URL', 'https://api.example.com');

// ✅ Now you can use the constant
echo API_URL;
?>

Solution 2: Use define() with Conditional Check

<?php
// ✅ Check if constant exists before defining
if (!defined('API_URL')) {
    define('API_URL', 'https://api.example.com');
}

echo API_URL;
?>

Solution 3: Use Class Constants

<?php
// ✅ Define constants in a class
class Config {
    const DB_HOST = 'localhost';
    const DB_NAME = 'myapp';
    const API_KEY = 'your-api-key';
}

// ✅ Access class constants
echo Config::DB_HOST;
echo Config::DB_NAME;
?>

Solution 4: Use PHP 8.1+ Enum Constants

<?php
// ✅ Use enums for related constants (PHP 8.1+)
enum Status: string {
    case PENDING = 'pending';
    case APPROVED = 'approved';
    case REJECTED = 'rejected';
}

// ✅ Use enum constants
echo Status::PENDING->value;
?>

Solution 5: Check Constant Definition

<?php
// ✅ Verify constant exists before using
if (defined('API_URL')) {
    echo API_URL;
} else {
    echo "Constant API_URL is not defined";
}

// ✅ Or use a default value
$apiUrl = defined('API_URL') ? API_URL : 'https://default-api.com';
echo $apiUrl;
?>
Gautam Sharma

About Gautam Sharma

Full-stack developer and tech blogger sharing coding tutorials and best practices

Related Articles

php

Fix: PHP file not executing on server error - Quick Solutions

Quick guide to fix 'PHP file not executing on server' errors. Essential fixes with minimal code examples.

January 8, 2026
php

How to Solve PHP File Not Executing on Server Problems - Essential Fixes

Essential guide to solve 'PHP file not executing on server' problems. Essential fixes with minimal code examples.

January 8, 2026
php

Fix: PHP mail() not working error

Quick fix for PHP mail() not working error. Learn how to configure PHP mail settings and use alternatives like SMTP for reliable email delivery.

January 8, 2026