PHP Constants

Value of PHP Constants can not be changed during the execution of the script. PHP Constants is an identifier or name which contains unchanged value.

Constants are like variables but once Constants are defined they cannot be changed or undefined. php variables can be changed any time.php variables can be defined by $ sign when PHP Constants can be defined as per as below two methods.

  1. define() function
    PHP Syntax:  define(name, value, case-insensitive);
    where,
    name parameter is name of the constant.
    value parameter is value of the constant.
    case-insensitive parameter is whether the constant name should be case-insensitive. Default is false
    PHP Code Example :
    <?php
        define("CONSTNAME", "Learn PHP constant by aryatechno!");
        echo CONSTNAME;
    ?>
    Output:
    Learn PHP constant by aryatechno!
     
  2. const keyword
    PHP Syntax: const name = value;
    PHP Code Example :
    <?php
        const VARNAME = "Learn PHP constant by aryatechno!";
        echo CONSTNAME;
    ?>
    Output:
    Learn PHP constant by aryatechno!

A valid constant name starts with a letter or underscore. There is  no $ sign before the constant name.

⇒ Constants are automatically global and can be used across the entire script.
PHP Code Example :
We can access constant inside function even if it is defined outside the function as per as below example.
<?php
    define("SHORTDESC", "Welcome to aryatechno tutorials!");
    function checkScope() {
      echo SHORTDESC;
    }
    checkScope();
?>

Output:
Welcome to aryatechno tutorials!

Difference between (Constant vs Variables) :

Constants Variables
  1. php constants are global by default.
  1. PHP Variables can be local, global or static.
  1. Once the constant is defined, it's value can not be changed.
  1. A variable can be undefined. A variable can be redefined again.
  1. Constant can be defined without dollar ($) sign.
  1. php variables can be defined by $ sign before variable name.
  1. Constants do not follow any variable scoping rules and they can be defined and accessed anywhere.
  1. PHP Variables can be declared anywhere in the php program code but they follow variable scoping rules.
  1. A constant can only be defined using define() function or const keyword.
  1. A variable can be defined by simple assignment (=) operator.
  1. Once Constants are defined they cannot be changed or undefined
  1. The value of the variable can be changed.

 

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

58017