Wednesday, July 16, 2014

Constant variables in PHP

Basic Concept
By declaring a variable as constant, it will available all over the program and only we can access it, cannot modify it.

In PHP we can declare a constant variable in two ways. That are using define() function and const keywords.

Before going to see deep difference between these, first look a simple program using these two methods.

Example 1:
<?php
define('PIE',3.143);
const SHAPE='Circle';

function fun()
{
       echo PIE.'<br />';
       echo SHAPE;
}

fun();
?>

Output:
3.143
Circle
?>

On above example there no difference between using define() and const. But it has following notable differences.

1. const execute on compile time and define() execute on run time. That is we cannot declare const under a function or and conditional statement like "if".

2. We cannot declare define() in class, but can declare const.

See the below complex example which is using define() and const in all possible manners.

Example 2:
<?php
define('REGISTER_NO',90323540126);  // Declaring a constant using define keyword in global.
const NAME = 'Ramasamy Kasi';          // Declaring a constant using const keyword in global.
const ROLL_NO = 35;

function fun()
{
define('DEPARTMENT','Computer Science'); // Declaring a constant using define inside a funtion.
// const TOTAL = 450;    // Try to declare a constant using const inside a funtion. ITS WRONG.

echo REGISTER_NO.'<br />'; // Accessing consatants inside a function.
echo NAME.'<br />';
}

class Test
{
// define('AVERAGE',90) // Try to declare a constant using define inside a class. ITS WRONG.
const SEMESTER = 1;          // Declaring a constant using const inside a class.

function sample()
{
echo self::SEMESTER.'<br />';          // WAY 1: Accessing class constant.
}
}

fun(); // Calling function.
echo ROLL_NO.'<br />'; // Accessing constant, which is created in side a function.
echo DEPARTMENT.'<br />'; // Accessing constant, which is created on global.
$obj=new Test();
$obj->sample(); // Calling class function.
echo TEST::SEMESTER; // WAY 2: Accessing class constant.
?>

Output:
90323540126
Ramasamy Kasi
35
Computer Science
1
1

No comments:

Post a Comment

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS&l...