Back to course

Constants: Defining Fixed Values

PHP: The Complete 0 to Hero Bootcamp

6. Constants: Defining Fixed Values

Constants are identifiers for simple values that cannot be changed during the script's execution. Unlike variables, constants do not start with a dollar sign.

Defining Constants

We use the built-in define() function to create a constant. By convention, constant names are typically written in uppercase.

php

User limit: " . MAX_USERS; // Attempting to redefine a constant results in an error // define("SITE_NAME", "New Site"); // Fatal error ?>

Class Constants (Introduced in OOP)

Constants can also be defined inside classes using the const keyword.

Magic Constants

PHP provides several predefined constants, called 'Magic Constants', which change based on where they are used. They are case-insensitive.

ConstantDescription
__LINE__The current line number of the file.
__FILE__The full path and filename of the file.
__DIR__The directory of the file.
__FUNCTION__The function name.

php

The file path is: " . __FILE__; ?>