phpicoder Nov 2, 2021 php

Hi guys, in this tutorial we will learn PHP Constant Variable.

A constant is  a name or identifier for a fixed value. Constant variables are like, once defined, they cannot be obscured or changed.

Constants are very useful for storing changing data while the script is running. Common examples of such data include configuration settings such as database username and password, base url, locations etc.

php constant name valid starts with a letter or underscore (no $ sign before the constant name).

Syntax:
define(name, value, case-insensitive)

name: It specifies the constant name.
value: It specifies the constant value.
case-insensitive: Specifies whether it is not static case-sensitive. The default value is incorrect. That means it is basically case sensitive. Let's look at an example for a PHP static definition using defined ().

Constant Example:

Example:
<?php
  // Defining constant
  define("tutorial", "constant tutorials");
 
  // Using constant
  echo 'This is a ' .tutorial; // case-insensitive
?>
Output:
This is a constant tutorials

Constant a Arrays Example: 

<?php
  define("weekend", [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday"
  ]);
  echo "Today is a ".weekend[0];
?>
Output:
Today is a Monday

Constants are Global Example: 

<?php
  define("tutorial", "This is a global constant tutorials");

  function getTutorial() {
    echo tutorial;
  }
 
  getTutorial();
?>
Output:
This is a global constant tutorials

I hope this tutorial help for you.