October 29, 2026

PHP – Constants

A constant in PHP is an identifier or name for a simple value. The value of a constant cannot be changed during the execution of the program. Normally, a constant  is case-sensitive. By convention, constants are always uppercase. A constant could start with an underscore or letter, then followed by a number of letters and underscores. Once a constant is defined, it cannot be undefined.

To define a constant in your script, you use the script() function. Then to retrieve the value of a constant, you have to specify the name of the constant. Unlike variables, constant does not need start with the $ sign. Also, to get the name of the constant, you can use the constant() function, specifying the  the constant as  parameter.

The example below illustrate how constant work

<?php
   define("MAXSCORE", 100);
   
   echo MAXSCORE;
   echo constant("MAXSCORE"); // same thing as the previouS
?>

 

Difference Between Constants and Variables

  • Constants are not named using the $ sign as the first character but variables must begin with the $ sign
  • Constant must be defined before use using the define() function but variables need not be defined
  • Constants may be defined and accessed anywhere in the program regardless of the variable scoping rules
  • A Constant once set may not be redefined or undefined

 

PHP Magic Constants

These are predefined constants which are available to PHP scripts. There are five of these type of constant whose value depends on where it is used. They are also case sensitive.

Some of these constants are given below:

SN Name & Brief Description
1 __LINE__

Gives the value of the current line number of the file.

2 __FILE__

Gives the full path and filename of the file. If it is used inside an include, the name of the included file is returned. Since PHP version 4.0.2, __FILE__ always contains an absolute path whereas in older versions it contained relative path in some circumstances.

3 __FUNCTION__

Gives the function name. (Added in PHP 4.3.0). As of PHP version 5, this constant gives the function name as it was declared (case-sensitive). In PHP 4 its value is always lowercase.

4 __CLASS__

Gives the class name. (Added in PHP 4.3.0). As of PHP version 5 this constant gives the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercase.

5 __METHOD__

Gives the class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).