Find the output of PHP programs | static variables, classes, methods | Set 2: Enhance the knowledge of PHP static variables, classes, methods concepts by solving and finding the output of some PHP programs.
Question 1:
<?php
class Sample
{
private $count = 0;
public static function AddCount()
{
self::$count = self::$count + 1;
}
public static function PrintCount()
{
echo "<br>Count is: " . self::$count;
}
}
Sample::AddCount();
Sample::AddCount();
Sample::AddCount();
Sample::PrintCount();
?>
Question 2:
<?php
function fun()
{
static $VAR = 0;
$VAR = $VAR + 1;
return $VAR;
}
fun();
fun();
$count = fun();
echo "Function fun() called " . $count . " times";
?>
Question 3:
<?php
static class sample
{
function fun()
{
static $VAR = 0;
$VAR = $VAR + 1;
return $VAR;
}
}
Sample::fun();
Sample::fun();
$count = Sample::fun();
echo "Funtion fun() called " . $count . " times";
?>
Question 4:
<?php
class Sample
{
function fun()
{
static $VAR = 0;
$VAR = $VAR + 1;
return $VAR;
}
}
Sample::fun();
Sample::fun();
$count = Sample::fun();
echo "Funtion fun() called " . $count . " times";
?>
Question 5:
<?php
static $VAR = 0;
function fun()
{
$VAR = $VAR + 1;
return $VAR;
}
fun();
fun();
fun();
echo "Funtion fun() called " . $VAR . " times";
?>
Answer 1:
Output:
Explanation:
The above program will generate syntax error because we cannot access a non-static member of a class form static function.
Answer 2:
Output:
Explanation:
In the above program, we created a function fun() that contains a static variable $VAR and increased by 1 on every function call, and return the value. We called function fun() three times then "Function fun() called 3 times" message will be printed on the webpage.
Answer 3:
Output:
Explanation:
The above program will generate syntax error because we cannot create declared a class as static in PHP.
Answer 4:
Output:
Explanation:
In the above program, we created a class Sample that contains a function fun(). The function fun() that contains a static variable $VAR and increased by 1 on every function call, and return the value. We called function fun() three times then "Function fun() called 3 times" message will be printed on the webpage.
Answer 5:
Output:
Explanation:
In the above program we defined a static variable $VAR, and increased $VAR by 1 in the function fun(), the static variable $VAR and variable $VAR inside the function fun() are different. That's why "Function fun() called 0 times" message will be printed on the webpage.
need an explanation for this answer? contact us directly to get an explanation for this answer