PHP Tutorial: Constants

Constants

A constant is a name or an identifier for a simple value that cannot be change. 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.

There is a predefine function named define() in PHP. With this function you do not need to have a constant with $ unlike with variable. You can aslo use constant() function to read a constant's value.

define() function:

It is used to define a constant.

Syntax:

define(name, value, case-insensitive)

  • name: name of constant.
  • value: value for a constant.
  • case-insensitive: Specifies whether the constant name should be case-insensitive. Default is false.

Example:

<?php

define("MESSAGE", "Welcome to Quizsolution!");

echo MESSAGE;

?>

 

constant() function:

This function will return the value of the constant.

This is useful when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored in a variable or returned by a function.

Example:

<?php

define("COST", 50);

echo COST;

echo constant("COST ");

?>

In this example both the echo statements returns the same value.

Constants are automatically global and can be used across the entire script. If once you define the constant you can use it anywhere in the script.

Example:

<?php

define("MESSAGE", "Welcome to Quizsolution!");

function myTest() {

    echo MESSAGE;

}

myTest();

?>

Next Topic