QA
Beginner LevelPHP 8+

What is the difference between defining constants using define("FOO", 1) versus the const keyword?

❓ Interview Prompt: Compare const (compile-time, class scope) vs define() (runtime function, conditional definition).

PHP provides two ways to declare constants:

1. 'const' Keyword:

•
Compile-Time: Evaluated at compile time.
•
Scope: Can be used inside classes ('public const TAX_RATE = 0.20;') and interfaces.
•
Constraint: Cannot be declared inside conditional blocks like 'if ()' or functions.

2. 'define()' Function:

•
Run-Time: Evaluated at runtime when the function executes.
•
Scope: Always global. Cannot be used inside class definitions.
•
Flexibility: Can be called conditionally inside 'if' blocks or using dynamic string names ('define("APP_" . $env, 1)').

Code Implementation Example

php
<?php
// 1. const keyword for class constants and compile-time globals
const APP_VERSION = "2.0.0";

class Config {
    public const DB_HOST = "localhost";
}

// 2. define() for runtime conditional definition
if (getenv('ENV') === 'production') {
    define('API_URL', 'https://api.company.com');
} else {
    define('API_URL', 'http://localhost:8080');
}
💡Using const for class constants and define() for conditional runtime configuration.
🎯 Interview Key Takeaway

Use const for class constants and compile-time constants; use define() for conditional runtime definitions.

#Constants#const#define#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?