PHP Constant

 

In PHP, a constant is an identifier (name) for a simple value that cannot be changed or redefined during the execution of a script. Unlike variables, constants do not use a dollar sign ($) and are automatically global across your entire application.

 

Constant vs. Variable
 
FeatureConstantVariable
SyntaxNo $ sign (e.g., NAME)Starts with $ (e.g., $name)
ValueFixedChangeable
ScopeAlways GlobalLocal by default 
AssignmentVia define() or constVia = operator

 

To create a Constant, the syntax is:

Define(name, value, case-insensitive)

Defining a Constant

A constant is an identifier whose value cannot be changed once it is defined. In PHP, constants are created with the define() function or the const keyword.

<?php
define("SCHOOL", "Computer Mafia");
const PI = 3.14;
echo SCHOOL;   // Computer Mafia
echo PI;       // 3.14
?>

Rules for Constants

  • A constant name does not start with a $ sign.
  • It must start with a letter or underscore.
  • By convention, constant names are written in UPPERCASE.
  • Constants are global and can be used anywhere in the script.
  • Once defined, a constant cannot be changed or undefined.

Constant vs Variable

  • A variable starts with $ (e.g. $marks); a constant does not.
  • A variable’s value can change; a constant’s cannot.
  • Variables are created by assignment; constants by define() or const.

Predefined (Magic) Constants

PHP has built-in constants such as PHP_VERSION, __LINE__ (current line number) and __FILE__ (current file path).

Important Questions

Q. How do you define a constant in PHP?
Ans. Using define(“NAME”, value); or const NAME = value;

Q. Write two differences between a constant and a variable in PHP.
Ans. A variable starts with $ and its value can change, while a constant has no $ and its value cannot be changed.

Q. What does __LINE__ return?
Ans. The current line number of the script.