HOME HTML EDITOR C JAVA PHP

PHP Constants

Constants are like variables, except that once they are defined, they cannot be changed or undefined. A constant name does not need a leading dollar sign ($).

1. Create a PHP Constant

To create a constant, use the define() function. It takes two main parameters: the name of the constant and its value.

<?php
  // define(name, value)
  define("GREETING", "Welcome to ExpertsJava!");
  echo GREETING;
?>

2. PHP const Keyword

You can also create a constant using the const keyword. While define() can be used anywhere, const is often used inside classes but works in the global scope too.

<?php
  const MYCAR = "Volvo";
  echo MYCAR;
?>

3. Constants are Global

Constants are automatically global and can be used across the entire script, even inside functions, without using the global keyword.

<?php
  define("SITE_URL", "https://expertsjava.com");

  function myTest() {
    echo SITE_URL; // Constant is accessible here
  }

  myTest();
?>

4. PHP Constant Arrays

You can also create an array constant using the define() function.

<?php
  define("cars", [
    "Alfa Romeo",
    "BMW",
    "Toyota"
  ]);
  echo cars[0];
?>
Important Rule: By convention, constant names are always written in UPPERCASE letters to distinguish them from variables.