Home Blog Constant in PhP

Constant in PhP

0
Constant in PhP

A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name). Note: Unlike variables, constants are automatically global across the entire script.

Syntax

define(name, value, case-insensitive)

  • Constants are PHP container that remains constant and never change
  • Constants are used for data that is unchanged at multiple places within our program
  • Variables are temporary storage while Constants are permanent
  • Use Constants for values that remain fixed and referenced multiple times

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

Valid and Invalid Constant declaration

<?php
//valid constant names
define('ONE', "first value");
define('TWO', "second value");
define('SUM 2',ONE+TWO);

//invalid constant names
define('1ONE', "first value");
define(' TWO', "second value");
define('@SUM',ONE+TWO);
?>

Constants are Global

Constants are automatically global and can be used across the entire script. The example below uses a constant inside a function, even if it is defined outside the function:

<?php
define("GREETING", "Welcome to studywarehouse.com!");

function myTest() {
    echo GREETING;
}
 
myTest();
?>

 

LEAVE A REPLY

Please enter your comment!
Please enter your name here