Wednesday, January 21, 2015

[PHP][Tutorial] Usage of constant variable in php.

Constant variable is a variable whose value cannot be changed once it has been assigned a value. A constant in php is an identifier (name) for a simple value,
start with a letter or underscore (not start with a dollar sign), followed by any number of letters, numbers, or underscores.

Syntax to Define constant variable outside a class: (change the orange text to you text:)
define('CONSTANT_NAME', ' constant value');
Define constant variable within a class:(change the orange text to you text:)
const CONSTANT_NAME = constant value;

There is a good example by wbcarts at juno dot com, can explain how to use the constant variable clearly:
<?php
define('MIN_VALUE', '0.0');   // RIGHT - Works OUTSIDE of a class definition.
define('MAX_VALUE', '1.0');   // RIGHT - Works OUTSIDE of a class definition.


//const MIN_VALUE = 0.0;         WRONG - Works INSIDE of a class definition.
//const MAX_VALUE = 1.0;         WRONG - Works INSIDE of a class definition.


class Constants{
  //define('MIN_VALUE', '0.0');  WRONG - Works OUTSIDE of a class definition.
  //define('MAX_VALUE', '1.0');  WRONG - Works OUTSIDE of a class definition.


  const MIN_VALUE = 0.0;      // RIGHT - Works INSIDE of a class definition.
  const MAX_VALUE = 1.0;      // RIGHT - Works INSIDE of a class definition.


  public static function getMinValue()
  {
    return self::MIN_VALUE;
  }

  public static function getMaxValue()
  {
    return self::MAX_VALUE;
  }
}

echo “Value of ”.MIN_VALUE.”<br />”;
echo “Value of ”. MAX_VALUE.”<br />”;
?>

Result :
Value of 0.0
Value of 1.0

Reference:
http://php.net/manual/en/language.constants.php
http://www.businessdictionary.com/definition/constant-variable.html#ixzz3PRtfxwqi

No comments :

Post a Comment