Signup/Sign In

PHP Constants

Constants are variables whose value cannot be changed. In other words, once you set a value for a constant, you cannot change it.

In PHP, there are two ways to define a constant:

  1. Using the define() method.
  2. Using the const keyword.

Another very important point to remember is that while naming a constant, we don't have to use $ symbol with the constant's name.


Using define()

Below is the syntax for using the define() function to create a constant.

define(name, value, case-insensitive)

Parameters:

  1. name: Name of the constant
  2. value: Value of the constant
  3. case-insensitive: Specifies whether the constant name is case sensitive or not. It's default value is false, which means, by default, the constant name is case sensitive.

Time for an Example

Below we have a simple example where we have not mentioned the parameter case-insensitive, hence it will automatically take the default value for that.

<?php
    define(OMG, "Oh! my God.");
    echo OMG;
?>

Oh! my God.

For the above constant definition, if we try to use the following statement we will get an error, because the constant OMG is case sensitive.

<?php
    define(OMG, "Oh! my God.");
    echo omg;
?>

omg

echo will consider it as a string and will print it as it is, with a subtle NOTICE saying that the string variable is not defined.

Now let's see another example where we will specify the case-insensitive parameter.

<?php
    define(OMG, "Oh! my God.", true);
    echo omg;
?>

Oh! my God.


Using the const Keyword

We can also define constants in PHP using the const keyword. But we can only use the const keyword to define scalar constants, i.e. only integers, floats, booleans and strings, while define() can be used to define array and resource constants as well, although they are not used oftenly.


Time for an Example

<?php
    const OMG = "Oh! my God.";  
    echo OMG;
?>

Oh! my God.

When we define a constant using the const keyword, the constant name is always case sensitive.