0
0
PhpHow-ToBeginner · 3 min read

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); where CONSTANT_NAME is the name and value is the constant's value.
  • Using const keyword: 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 const inside 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

ConceptUsageNotes
Define constantdefine('NAME', value);Function, works anywhere
Define constantconst NAME = value;Keyword, used in global scope or classes
Access constantNAMENo $ sign, case-sensitive
Redefine constantNot allowedConstants cannot be changed once set
Case sensitivitydefine() is case-sensitive by defaultCan 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.