Beginner Fundamentals
PHP Constants
A constant is a value that never changes while the program runs. Unlike variables, constants do not use a dollar sign and cannot be reassigned.
Defining with define()
The define() function creates a constant at runtime.
<?php
define("SITE_NAME", "My Website");
echo SITE_NAME; // My Website
Defining with const
The const keyword defines a constant at compile time, often used at the top level or inside classes.
<?php
const MAX_USERS = 100;
echo MAX_USERS; // 100
Rules for constants
- No dollar sign in the name.
- By convention, names are written in uppercase.
- The value cannot change once set.
Magic constants
PHP provides special predefined constants that change depending on where they are used.
<?php
echo __LINE__; // current line number
echo __FILE__; // full path of the file
echo __DIR__; // directory of the file
These are useful for debugging and logging. Note they begin and end with two underscores.