Constants in PHP language
Notes:
PHP Constants
Variable:
Variable is a named memory location, whose value may change during the execution of a program.
Constant:
Constant is a named memory location, whose value never changes during the execution of a program.
I.e. constants stay constant whereas variables vary.
Declaring a variable or a constant: means allocating a memory location for some data
Initializing a variable or a constant: means putting an initial data value within that allocated memory location
Assigning a variable or a constant: means putting a new data value within that allocated memory location
Syntax:
// declaration and initialization of a constant
const NAME_OF_CONSTANT = value;
// declaration and initialization of a constant
define(“NAME_OF_CONSTANT”,value, bool case_insensitive) : bool;
Note:
No comma separated variable or constants allowed, like in other languages
Variables must be initialized, before using them.
Constants must and should be initialized, when they are declared or defined
While accessing a variable directly within a string, it’s recommended to enclose a variable within {}
Constants are not recognized when used inside a string.
Example code:
<?php
/*
$playerScore = 0;
echo $playerScore,"<br/>";
$playerScore = 20;
echo $playerScore,"<br/>";
echo "<br/>";
const PI = 3.142;
echo PI,"<br/>";
// PI = 4.142; // error
define("SCREEN_WIDTH",600);
echo SCREEN_WIDTH,"<br/>";
// SCREEN_WIDTH = 400; // error
*/
/*
const PI = 3.142;
echo PI,"<br/>";
// echo pi,"<br/>"; // case sensitive
define("SCREEN_WIDTH",600,true);
echo SCREEN_WIDTH,"<br/>";
echo screen_width,"<br/>";
echo sCREEN_width,"<br/>";
echo screen_WIDTH,"<br/>";
*/
/*
$isGameOver;
$isGameOver=true;
echo $isGameOver,"<br/>";
const PI = 3.142;
echo PI,"<br/>";
*/
$isGameOver=true;
echo "is game over = {$isGameOver}","<br/>";
const PI = 3.142;
echo "PI value is = {PI}","<br/>";
?>
Interview Questions:
1. PHP stands for ______________
a. Hypertext Preprocessor
b. Preprocessor Hypertext
c. Personal Home Processor
d. Personal Hypertext processor
Ans: a