PHP 7 Constants

A constant is a variable that has a constant value. Constants have same rules as PHP variables, except it does not has a leading dollar sign ($) and the constants once defined, then it can globally accessible across the script. The configuration file is a good example of constants. The username, password, database name are only once defined in a configuration file and cannot be changed throughout the script and these are globally accessible.

Features of PHP Constants

  • Constant value cannot be changed during the execution of the script.
  • Once a constant is initialized, it cannot be reset to another value.
  • Constant name is accessed globally by default.
  • Once a constant is defined in configuration file we can call this all over the project without redeclaring this.
  • Generally, a constant name has defined in upper case letter. We can also follow the same rule for the constant name as for the variable except it does not have a leading dollar sign
  • PHP 7 provides feature to define array constant using define function.

In PHP, there are two ways for creating a constant - class const modifier and define function.

Class Const Modifier

The class const modifier is used within the class.

Syntax of const

class ClassName
    function func_name(){
echo ClassName::CONSTANT_NAME;

As you can show in the above example, a class constant is referenced in the same way like a static property.


class Estimate
    const RATE = '100';
    const INC = 'Indian Rupee';
    function cal_estimate(){
echo Estimate::RATE;
echo Estimate::INC;

define function

PHP define function is used to create local and global constants.

Syntax of PHP Constant

define("CONSTANT_NAME", "CONSTANT_VALUE", "Case sensitivity");

The constant name is always in uppercase and constant value can be in any scalar data type, like integer, string, float. Case sensitivity is an optional parameter. The defined constant is case sensitive by default. To make this case insensitive, you need to define case sensitivity value to true.


    define("STATUS", "What is in your mind");
    define("SITE", "eTutorials Point");
    echo STATUS;
    echo '<br/>';
    echo SITE;

PHP 7 Array Constants

In PHP 7, we can create array constants using define function.


	define("dog", ["Boxer", "Akita", "Bulldog"]);
	echo dog[1];

Read more articles

General Knowledge

Learn Popular Language