How to Define Constant in PHP: Syntax and Examples
In PHP, you define a constant using the
define() function or the const keyword. Constants hold values that cannot change during script execution and are accessed without a dollar sign.Syntax
There are two main ways to define constants in PHP:
- Using
define()function:define('CONSTANT_NAME', value);whereCONSTANT_NAMEis the name andvalueis the constant's value. - Using
constkeyword:const CONSTANT_NAME = value;used inside or outside classes.
Constants are case-sensitive by default and do not use a dollar sign.
php
<?php define('SITE_NAME', 'MyWebsite'); const VERSION = '1.0';
Example
This example shows how to define and use constants with both define() and const. It prints the constant values.
php
<?php // Define constant using define() define('GREETING', 'Hello, world!'); // Define constant using const const PI = 3.14159; // Use constants echo GREETING . "\n"; echo "Value of PI: " . PI . "\n";
Output
Hello, world!
Value of PI: 3.14159
Common Pitfalls
Common mistakes when defining constants include:
- Using a dollar sign (
$) before the constant name, which is incorrect. - Trying to redefine a constant after it is set, which is not allowed.
- Using
constinside functions (not allowed in PHP). - Confusing case sensitivity;
define()constants are case-sensitive unless specified otherwise.
php
<?php // Wrong: Using $ with constant name // echo $GREETING; // This will cause an error // Right: Use constant name without $ echo GREETING; // Wrong: Redefining constant // define('GREETING', 'Hi again!'); // This will not change the value // Right: Define once only
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| Define constant | define('NAME', value); | Function, works anywhere |
| Define constant | const NAME = value; | Keyword, used in global scope or classes |
| Access constant | NAME | No $ sign, case-sensitive |
| Redefine constant | Not allowed | Constants cannot be changed once set |
| Case sensitivity | define() is case-sensitive by default | Can be made case-insensitive with 3rd param (deprecated) |
Key Takeaways
Use
define() or const to create constants in PHP.Constants do not use a dollar sign and cannot be changed once defined.
Avoid redefining constants or using
const inside functions.Access constants by their name directly, respecting case sensitivity.
Use
const for class constants and define() for global constants.