What are variables and constant and its difference in php ?

Constant

  • A Constant is value the cannot be altered with in the normal execution of the program.
  •  A constant is a case-sensitive and by convention the constants are always  in upper case .
  • Constant can have the global scope and can be called anywhere in the program .
  • The constant starts with letters or underscore , followed by the numbers of letters , numbers ,or underscore .

Syntax :

define(name , value ); 

Example :
<?php
// Valid declaration
define(‘MY_PHP’ , ‘Constant with php’); 

// Generate output 

  echo MY_PHP ; 

// invalid declaration
define(’99PHP’ , ‘Constant with php’); 

?>
Output : 
Constant with php

Constant as Global Scope 

<?php
function constant_global() {
    echo MY_PHP;
}
constant_global();
?>
Same output as above .

Variables 

  • The variables are declared by dollar sign ($) followed by the name of variables , i.e alpha numeric characters along with underscore .
  • It cannot be started with the number .
  • Variables are case-sensitive , i.e $a and $A , both treated as different variables . 

<?php
   $var1 = ‘Learn Php’;
   $var2 = ‘ with php interview questions ‘;
   echo “$var1, $var2”;      // outputs “Learn Php with php interview questions  “

   $1var  = ‘Learn’;     // invalid; starting with a number
   $_4var = ‘php’;    // valid; starting with an underscore

?>

Leave a Reply

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