Advertisement

Google Ad Slot: content-top

PHP Constants


Constants are similar to variables except that, once they are defined, their values cannot be changed during the execution of the script. Constants are useful for defining values that are used throughout a program but should remain the same.


Defining Constants



1. Using define() Function:


  • The define() function is used to create a constant.
  • Constants do not use the $ symbol when being defined or used.
  • They can store scalar values (strings, integers, floats, booleans) or arrays (from PHP 7).


Syntax:


define(name, value)


  • name: Specifies the name of the constant
  • value: Specifies the value of the constant
Example
<?php
// case-sensitive constant name
define("SITE_NAME", "MyWebsite");
echo SITE_NAME; // Outputs: MyWebsite
?>
Try it yourself

Note

Constant name is case-sensitive.

2. Using const Keyword (More common for defining class constants):


     Constants can also be defined using the const keyword

Example
<?php
const MYCAR = "Volvo";
echo MYCAR;
?>
Try it yourself

Note

const vs. define()

  • const cannot be created inside another block scope, like inside a function or inside an if statement.
  • define can be created inside another block scope.


PHP Constant Arrays


From PHP 7, you can create an Array constant using the define() function.

Example
<?php
define("COLORS", ["Red", "Green", "Blue"]);
echo COLORS[0]; // Outputs: Red
?>
Try it yourself

Constants are Global


Constants are automatically global and can be used across the entire script, including within functions and methods.

Example
<?php
define("GREETING", "Welcome to whereisstuff.com!");
function myTest() {
echo GREETING;
}
myTest();
?>
Try it yourself

Note

Only defined constants are have Global scope.