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
constworks at the top level and in classes;define()can be used insideifblocks
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.