What will be the output of following PHP code snippet?
<?php
$i=0;
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";
?>
Content of "inc.php" is given below..
<?php
$i++;
echo "Included :: $i";
?>
Answer ::
---------------
Included :: 1
1
Included :: 2
2
2
Included :: 3
3
Discussion ::
-------------
The first "include_once()" includes the file once which increments the value of $i to 1. Hence the first output is shown from first inclusion of inc.php.
Next "include()" statement again includes the inc.php which increments the $i to 2 and the output follows.
Next "include_once()" does not include the "inc.php" as it was previously included... Hence the old value of $i [2] is retained.
The last "include" again includes the "inc.php" and hence increments the $i again to make it to 3.
AGain check the output of the following code snippet
<?php
$i=0;
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
?>
The output ::
---------------
Included :: 1
1
1
Discussion ::
---------------
The first "include()" includes the file "inc.php" which increments the value of $i to 1 and prints the first line as shown in the output above.
Next "include_once()" does not include the file again ... hence the last value of $i (1) is retained.
<?php
$i=0;
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
include( "inc.php");
echo "$i";
?>
Content of "inc.php" is given below..
<?php
$i++;
echo "Included :: $i";
?>
Answer ::
---------------
Included :: 1
1
Included :: 2
2
2
Included :: 3
3
Discussion ::
-------------
The first "include_once()" includes the file once which increments the value of $i to 1. Hence the first output is shown from first inclusion of inc.php.
Next "include()" statement again includes the inc.php which increments the $i to 2 and the output follows.
Next "include_once()" does not include the "inc.php" as it was previously included... Hence the old value of $i [2] is retained.
The last "include" again includes the "inc.php" and hence increments the $i again to make it to 3.
AGain check the output of the following code snippet
<?php
$i=0;
include( "inc.php");
echo "$i";
include_once( "inc.php");
echo "$i";
?>
The output ::
---------------
Included :: 1
1
1
Discussion ::
---------------
The first "include()" includes the file "inc.php" which increments the value of $i to 1 and prints the first line as shown in the output above.
Next "include_once()" does not include the file again ... hence the last value of $i (1) is retained.
No comments:
Post a Comment