agyanadda@gmail.com

PHP Constants

Strings and Numbers 1 min read Updated Dec 1, 2026 Topic 10 of 36

A constant is a value that cannot change while the script runs — perfect for settings.

Create constants

define('SITE_NAME', 'AgyanAdda');
const GST_RATE = 18;
  • No $ sign
  • Use UPPERCASE names by convention
  • Available everywhere, even inside functions
  • const works at the top level and in classes; define() can be used inside if blocks

Check a constant

defined('SITE_NAME') returns true/false.

Magic constants

PHP fills these automatically:

Constant Value
__DIR__ folder of the current file
__FILE__ full path of the current file
__LINE__ current line number
PHP_VERSION PHP version
PHP_EOL new line character

require __DIR__ . '/config.php'; is the safest way to include files.

Example

Example — Site settings with constants PHP
<?php
define('SITE_NAME', 'AgyanAdda');
const GST_RATE = 18;
const SUPPORT_EMAIL = 'support@example.com';

function priceWithGst(float $price): float
{
    return $price + $price * GST_RATE / 100;
}

echo 'Welcome to ' . SITE_NAME . '<br>';
echo 'Course price: ₹' . priceWithGst(1000) . '<br>';
echo 'Contact: ' . SUPPORT_EMAIL . '<br>';
echo 'This file is in: ' . __DIR__ . '<br>';
echo 'PHP version: ' . PHP_VERSION;

Output: Welcome to AgyanAdda / Course price: ₹1180 / Contact: support@example.com / the folder path / the PHP version.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which is a correct way to create a constant?

Exercise 2 True / False

Constants start with a $ sign.

Exercise 3 Fill in the Blank

The magic constant ___ gives the folder of the current file.

Frequently Asked Questions

Keep them in a config or .env file outside the public folder (Laravel uses .env). Never commit real passwords to GitHub.