PHP Tutorial · PHP Basics · Lesson 11 of 38

PHP Constants

Define constants with const and define, and use magic constants.

Defining constants

A constant can't change once set. Use const (at the top level or in classes) or define():

Example 1Try it yourself
<?php
const APP_NAME = "ReadyCamel";
define("MAX_UPLOAD_MB", 10);
const COLORS = ["red", "green"];
echo APP_NAME, " allows ", MAX_UPLOAD_MB, " MB uploads\n";
echo COLORS[1], "\n";
var_dump(defined("APP_NAME"));

Output

ReadyCamel allows 10 MB uploads
green
bool(true)

Constants have no $ and are global. By convention their names are UPPERCASE.

Magic constants

PHP provides constants that change depending on where they're used, like __LINE__, __FILE__, __DIR__, __FUNCTION__ and __CLASS__:

Example 2Try it yourself
<?php
function whoAmI(): string
{
    return __FUNCTION__;
}
class Report
{
    public function name(): string
    {
        return __CLASS__ . "::" . __FUNCTION__;
    }
}
echo whoAmI(), "\n";
echo (new Report())->name(), "\n";
echo "This is line ", __LINE__, "\n";

Output

whoAmI
Report::name
This is line 15

Test yourself

Do PHP constants start with a $ sign?

  1. Yes
  2. No
Show answer

Answer: No