how to define constant in php

Introduction of Constant in php-: Like any other language constant are use in php.  Constants are like a variable that don’t change during execution. php refer to fixed value that do not change during the execution of a program. There are two type constant in php.

  1. define constant
  2. keyword constant

 

1 -:How to define constant -: Like the php variable the constant must be define before using the program for example

define ("name"," value",case-insensitive);

In this example name is the constant name and value are the constant value. case-insensitive means here the defining the constant are case sensitive or not For better understand we take a example simple define

<?php  
  define("alert","Welcome Netnic");
  echo alert;
?>  

The out put of this program

Welcome Netnic

With no case sensitive example

 <?php
   define("ALERT","Welcome Netnic" true);//not case sensitive
   echo alert;
   echo ALERT; 
?>  

Output of this program

Welcome netnicwelcome netnic

Example of with case sensitive file name is netnic1.php

 <?php
  define("ALERT","Welcome Netnic"false);// case sensitive
  echo alert;
  echo ALERT; 
?>  

Output of this program

Welcome Netnic
Notice: Use of undefined constant message - assumed 'alert' 
in C:\wamp\www\netnic1.php on line 3 alert

 

2-: Keyword Constant  -: This type constant are define compile constant.It is a language construct not a function. keyword constant are better than define constant. It is not case sensitive for example

<?php
  define("ALERT","Welcome Netnic" true);//not case sensitive
  echo ALERT; 
?> 

output of this program

Welcome Netnic

 

Rules for defining constant in php -: Rules are the same as the variable defining.A constant name is case sensitive means color and Color are different.these are not same.

Magic constant in php -:There are another constant are use in php. These are the magic constant. php provide many predefined constant this is called the magic constant.These magic constant start and end with double (__). These are the

__Line__  magic constant -:This is represent current line function which is using.

__File __ magic constant -: Its represent full file path and file name.

__Dir__ magic constant -: Its represent full directory path.

__class__ magic constant -: Its represent current class path where is using.

__function__ magic constant –: Its represent the current function where it  is using.

__namespace__ magic constant -: Its represent the current namespace.

__method__magic constant -: Its represents the name of the class method where it is using.

__Trait__ magic constant -: Its represents the trait name where it is used.

 

 

Leave a Reply

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