PHP Constants

A constant is a name that holds a value, like a variable, but the value can not be changed after it is set. Constants are useful for fixed values like the site name, a tax rate or a version number.


Create a constant

There are two ways: the define() function and the const keyword.

<?php
define("SITE_NAME", "Tutorials Class");
const VERSION = "2.0";

echo SITE_NAME . " " . VERSION;
?>

Output:

Tutorials Class - Output Window

Tutorials Class 2.0

  • A constant name does not start with $.
  • By convention, names are written in capital letters, with underscores, like MAX_USERS.
  • Constant names are case-sensitive.
  • A constant is global. You can use it everywhere, even inside functions, without the global keyword.
  • Once set, you can not change it or delete it.
define()const
Where to useAnywhere, even inside an if conditionOnly at the top level of a file or class
NameCan be created with a variable nameMust be a fixed name
Class constantsNoYes

Check and read a constant

<?php
define("MAX_USERS", 100);

var_dump(defined("MAX_USERS"));
var_dump(defined("MIN_USERS"));

echo constant("MAX_USERS");
?>

Output:

Tutorials Class - Output Window

bool(true)
bool(false)
100

defined() checks if a constant exists. constant() gets the value when the name is stored as a string, see What is the constant() function?.


Class constants

<?php
class Math {
    const PI = 3.14159;
}

echo Math::PI;
?>

Output:

Tutorials Class - Output Window

3.14159


Magic constants

PHP has some special constants that change their value depending on where you use them. They start and end with double underscore.

ConstantValue
__LINE__The current line number of the file
__FILE__The full path and file name
__DIR__The folder of the file
__FUNCTION__The name of the current function
__CLASS__The name of the current class
<?php
echo "This is line number " . __LINE__;
?>

Output:

Tutorials Class - Output Window

This is line number 2


Useful built-in constants

  • PHP_VERSION: the version of PHP.
  • PHP_EOL: a new line character, useful in command line scripts.
  • PHP_INT_MAX: the biggest integer.
  • M_PI: the value of pi.

Next chapter: PHP Operators.


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
Write a program to print “Hello PHP” using variable
Write a program to print a string using echo+variable.
Write a program to print two variables in single echo
Interview Questions & Answers
How to check if a variable is empty in PHP?
Is PHP a case sensitive language?
What are the different data types in PHP?
How to define a Constant in PHP?
What is the difference between $var and $$var in PHP?
Which special characters are allowed in PHP variable names?
Can we print multiple variables in a single echo statement in PHP?