Thursday 10 December 2015

PHP CONSTANTS

Constant in PHP
Constants are PHP container that remain constant and never change
Constants are used for data that is unchanged at multiple place within our program.
Variables are temporary storage while Constants are permanent.
Use Constants for values that remain fixed and referenced multiple times.
Rules for defining constant:
Constants defined using define( ) function:
Name of the constant
Value of the constant
Syntax:
<?php
  define('ConstName', 'value');
?> 

Valid and invalid constant declaration
 //valid constant names
  define('ONE', "first value");
  define('TWO', "second value");
  define('SUM 2',ONE+TWO);
//invalid constant names
  define('1ONE', "first value");
  define('   TWO', "second value");
  define('@SUM',ONE+TWO);

Create a constant and assign your name
Example:
<?php
  define('NAME', “John");
  echo NAME;
?>
Output :John
In the above example
We define a constant using define( ) function. first argument for name of constant and second for its value=”john”.
Now we print the value. Pass name of constant inside print statement.

Write a Program to Print the Sum of two numbers using constant
<?php
define('ONE', 100);
define('TWO', 100);
define('SUM',ONE+TWO);
echo "Sum of two constant=".SUM;
?>
Output : Sum of two constant=200

Write a Program to Print the Sum of two numbers and assign the result in variable not in constant
<?php
define('ONE', 100);
define('TWO', 100);
$res= ONE+TWO;
echo "Sum of two constant=".$res;
?>
Output : Sum of two constant = 200