PHP Constants

A PHP constant is a name or an identifier for a simple value. A constant value cannot change during the execution of the script.

Rules About Constant

  • By default, a constant is case-sensitive.
  • By convention, constant identifiers are always uppercase.
  • A constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.
  • If you have defined a constant, it can never be changed or undefined.

define() Function to Create Constant In PHP

To define a constant you have to use define() function and to retrieve the value of a constant, you have to simply specifying its name. Unlike with variables, you do not need to have a constant with a $.

Syntax

define(name, value, case-insensitive)

Parameters

  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false
<?php
define("value", 100);//with case-sensitive name
 
    echo value;
?>

Run : http://ideone.com/loOavd

Tutorials Class - Output Window

100

<?php
define("VALUE", 100,true);//with case-insensitive name
 
    echo value;
?>

Run : http://ideone.com/b35n1R


constant() Function to read Constant Value

You can also use the function constant() to read a constant’s value if you wish to obtain the constant’s name dynamically.

<?php
define("value", 50);//with case-sensitive name
 
    echo value;
	echo "<br>";
    echo constant("value");
?>

Run : http://ideone.com/fpOLzH

Tutorials Class - Output Window

50
50


Constants are Global

Constants are automatically global and can be used across the entire script.

<?php
define("Value", 100);
 
function myGlobal() {
    echo Value;
}
 
myGlobal();
?>

Run : http://ideone.com/wIumDX

Tutorials Class - Output Window

100


Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
How to define a Constant in PHP?