Tuesday 21 July 2015

PHP Variable Interpolation

PHP supports interpolation of variables in between set of words to be printed to the browser using PHP output statements like echo(), print() and etc. There are two methods in variable interpolation. First method is to use variables in between string enclosed by double quotes which is shown as follows.
$name = "PHPPOT";
echo "I am reading $name"; // output: I am reading PHPPOT
Then, the variable interpolation can also be implemented with here document which contains several lines of string to be printed. PHP variables will be included to replace their value. A here document will be as follows to print the content as it is including line breaks, quotes and etc.
$myDoc = <<< EOD
I am reading PHPPOT
to know all about PHP
EOD;
echo $myDoc;
php_variable_interpolation
In another method of variable interpolation, the variables will be enclosed by curly braces to replace its value inside a word that is not separated by any white space. This can be clearly understood by the following example.
$name = "PHP";
echo "I am reading {$name}POT"; // output: I am reading PHPPOT
Here, in the above program, the variable $name is associated with the string POTwithout any white space. So that, the curly braces are needed around the variable name to distinguish both. Otherwise, execution process will look for the variable$namePOT, which is no more.

Note:

  • Among both of the above two methods, the first one is the easiest method.
  • Variable interpolation is not possible with in single quotes

0 comments:

Post a Comment