Defines a named constant at runtime.
What Is define() in PHP?
Defines a named constant at runtime.
Its syntax is:
define(string $constant_name, mixed $value, bool $case_insensitive = false): bool
Parameters:
$constant_name— Accepted as string; required argument.$value— Accepted as mixed; required argument.$case_insensitive— Accepted as bool; optional default false.
Return type: bool. A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.
Availability: Core PHP.
Example 1: Basic Usage
<?php
define("API_LIMIT", 100); echo API_LIMIT;
Output:
100
A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.
Example 2: A Different Input
<?php
define("FEATURE_ENABLED", true); var_dump(FEATURE_ENABLED);
Output:
bool(true)
A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.
Practical Example: Applying It in a Program
<?php
define("MAX_ITEMS", 20); $items = range(1, 12); echo count($items) <= MAX_ITEMS ? "Within limit" : "Too many";
Output:
Within limit
A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.
Important Behavior and Edge Cases
- Key behavior: A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.
- Environment: Core PHP.
Comparison With Related Functions
| Function | Purpose |
|---|---|
define() | Defines a named constant at runtime. |
const | const declares a constant at compile time; define() defines a named constant by a function call at runtime. |
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Ignoring this behavior: A constant cannot be redefined | A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions. |
Key Takeaways
- Defines a named constant at runtime.
- A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.
- Core PHP.
Summary: A constant cannot be redefined. Prefer meaningful, namespaced names to avoid collisions.