Static Variables and Variable Functions in PHP Solved Practice Questions

Introduction

Static variables retain their values between function calls instead of being reset every time a function runs. Variable functions allow you to call a function dynamically by storing its name in a variable. In this chapter, you will learn both concepts through practical PHP examples involving counters, calculations, employee records, and dynamic function calls. Static Variables and Variable Functions in PHP Solved Practice Questions with Solutions to help you to understand the concepts.

Question 1: Create a Static Variable Inside a Function

Problem Statement:
Create a function named countVisitors() that uses a static variable to count how many times the function is called.

PHP Solution:

<?php
function countVisitors() {
    static $count = 0;

    $count++;

    echo "Visitor Count: " . $count . "\n";
}

countVisitors();
countVisitors();
countVisitors();
?>

Sample Output:

Visitor Count: 1
Visitor Count: 2
Visitor Count: 3

Explanation:

  • The static keyword declares a static local variable.
  • $count is initialized only once.
  • Its value is retained between function calls.
  • Each call increases the existing value by one.

Concepts Covered:

  • Static variables
  • Function scope
  • Retaining variable values

Question 2: Create a Function Call Counter

Problem Statement:
Create a function named trackFunctionCalls() that displays how many times it has been executed using a static variable.

PHP Solution:

<?php
function trackFunctionCalls() {
    static $calls = 0;

    $calls++;

    echo "Function Executed: " . $calls . " Times\n";
}

trackFunctionCalls();
trackFunctionCalls();
trackFunctionCalls();
trackFunctionCalls();
?>

Sample Output:

Function Executed: 1 Times
Function Executed: 2 Times
Function Executed: 3 Times
Function Executed: 4 Times

Explanation:

  • $calls is a static variable.
  • Its value is not reset when the function finishes.
  • Every time the function runs, the counter increases.
  • This approach is useful for tracking function executions.

Concepts Covered:

  • Static counters
  • Function execution tracking
  • Static local variables

Question 3: Store a Running Total Using a Static Variable

Problem Statement:
Create a function named addSales() that accepts a sales amount and maintains a running total using a static variable.

PHP Solution:

<?php
function addSales($amount) {
    static $totalSales = 0;

    $totalSales = $totalSales + $amount;

    echo "Total Sales: " . $totalSales . "\n";
}

addSales(5000);
addSales(3000);
addSales(7000);
?>

Sample Output:

Total Sales: 5000
Total Sales: 8000
Total Sales: 15000

Explanation:

  • $totalSales stores the running sales total.
  • The first call adds ₹5,000.
  • The second call adds ₹3,000 to the existing total.
  • The third call adds ₹7,000.
  • The static variable preserves the accumulated value.

Concepts Covered:

  • Static variables
  • Running totals
  • Function parameters
  • Sales calculations

Question 4: Create a Static Variable for Employee ID Generation

Problem Statement:
Create a function named generateEmployeeID() that generates a new employee ID every time the function is called. Use a static variable to maintain the ID counter.

PHP Solution:

<?php
function generateEmployeeID() {
    static $id = 1000;

    $id++;

    return "EMP" . $id;
}

echo generateEmployeeID() . "\n";
echo generateEmployeeID() . "\n";
echo generateEmployeeID() . "\n";
?>

Sample Output:

EMP1001
EMP1002
EMP1003

Explanation:

  • $id starts with the value 1000.
  • The static variable retains its value between calls.
  • Each function call increases the ID by one.
  • The function returns a new employee ID.

Concepts Covered:

  • Static variables
  • ID generation
  • Return statements
  • String concatenation

Question 5: Create a Static Variable to Track Login Attempts

Problem Statement:
Create a function named trackLoginAttempts() that counts how many times a user attempts to log in.

PHP Solution:

<?php
function trackLoginAttempts() {
    static $attempts = 0;

    $attempts++;

    echo "Login Attempt: " . $attempts . "\n";
}

trackLoginAttempts();
trackLoginAttempts();
trackLoginAttempts();
?>

Sample Output:

Login Attempt: 1
Login Attempt: 2
Login Attempt: 3

Explanation:

  • $attempts is declared as a static variable.
  • Its initial value is zero.
  • Every function call increases the attempt count.
  • The previous count remains available during the next call.

Concepts Covered:

  • Static counters
  • Login attempt tracking
  • Function execution

Question 6: Call a Function Using a Variable

Problem Statement:
Create a function named welcomeMessage() that displays a welcome message. Store the function name in a variable and call the function using that variable.

PHP Solution:

<?php
function welcomeMessage() {
    echo "Welcome to PHP Programming!";
}

$functionName = "welcomeMessage";

$functionName();
?>

Sample Output:

Welcome to PHP Programming!

Explanation:

  • welcomeMessage() is a normal PHP function.
  • $functionName stores the function name as a string.
  • Adding parentheses to the variable calls the function.
  • PHP executes the function whose name is stored in the variable.

Concepts Covered:

  • Variable functions
  • Dynamic function calls
  • Function names as strings

Question 7: Call Different Functions Using Variable Functions

Problem Statement:
Create three functions named showPHP(), showPython(), and showJava(). Use a variable function to call the required function.

PHP Solution:

<?php
function showPHP() {
    echo "Learning PHP\n";
}

function showPython() {
    echo "Learning Python\n";
}

function showJava() {
    echo "Learning Java\n";
}

$selectedCourse = "showPython";

$selectedCourse();
?>

Sample Output:

Learning Python

Explanation:

  • Three separate functions are created.
  • $selectedCourse stores the name of the required function.
  • The variable function call executes showPython().
  • You can change the variable value to call another function.

Concepts Covered:

  • Variable functions
  • Dynamic function selection
  • Reusable functions

Question 8: Use a Variable Function for Mathematical Calculations

Problem Statement:
Create three functions named addition(), subtraction(), and multiplication(). Store the required function name in a variable and perform the selected calculation.

PHP Solution:

<?php
function addition($a, $b) {
    return $a + $b;
}

function subtraction($a, $b) {
    return $a - $b;
}

function multiplication($a, $b) {
    return $a * $b;
}

$operation = "multiplication";

$result = $operation(20, 5);

echo "Result: " . $result;
?>

Sample Output:

Result: 100

Explanation:

  • Three functions perform different calculations.
  • $operation stores the selected function name.
  • Calling $operation(20, 5) executes the selected function.
  • The returned result is stored in $result.

Concepts Covered:

  • Variable functions
  • Function parameters
  • Return values
  • Dynamic calculations

Question 9: Create a Dynamic Course Selection System

Problem Statement:
Create three functions named phpCourse(), pythonCourse(), and javaCourse(). Use a variable function to display the details of the selected course.

PHP Solution:

<?php
function phpCourse() {
    echo "Course: PHP\n";
    echo "Duration: 3 Months\n";
    echo "Mode: Classroom";
}

function pythonCourse() {
    echo "Course: Python\n";
    echo "Duration: 4 Months\n";
    echo "Mode: Online";
}

function javaCourse() {
    echo "Course: Java\n";
    echo "Duration: 5 Months\n";
    echo "Mode: Classroom";
}

$selectedCourse = "pythonCourse";

if (function_exists($selectedCourse)) {
    $selectedCourse();
} else {
    echo "Course Not Available";
}
?>

Sample Output:

Course: Python
Duration: 4 Months
Mode: Online

Explanation:

  • Three functions store different course details.
  • $selectedCourse contains the selected function name.
  • function_exists() checks whether the selected function is defined.
  • If the function exists, PHP calls it dynamically.
  • Otherwise, an error message is displayed.

Concepts Covered:

  • Variable functions
  • function_exists()
  • Dynamic function selection
  • Conditional statements

Question 10: Build an Employee Salary Calculator Using Variable Functions

Problem Statement:
Create separate functions to calculate gross salary and net salary. Use a variable function to select and execute the required salary calculation.

PHP Solution:

<?php
function calculateGrossSalary($basic, $allowance) {
    return $basic + $allowance;
}

function calculateNetSalary($basic, $allowance, $deduction) {
    return $basic + $allowance - $deduction;
}

$basicSalary = 30000;
$allowance = 5000;
$deduction = 3000;

$calculation = "calculateNetSalary";

if (function_exists($calculation)) {
    $result = $calculation(
        $basicSalary,
        $allowance,
        $deduction
    );

    echo "Net Salary: " . $result;
} else {
    echo "Calculation Function Not Found";
}
?>

Sample Output:

Net Salary: 32000

Explanation:

  • calculateGrossSalary() calculates basic salary plus allowance.
  • calculateNetSalary() subtracts deductions from total earnings.
  • $calculation stores the selected function name.
  • function_exists() verifies that the function is available.
  • The variable function executes the selected calculation and returns the result.

Concepts Covered:

  • Variable functions
  • Dynamic function execution
  • Salary calculations
  • Function parameters and return values
  • function_exists()

Key Takeaways

  • Static variables retain their values between function calls.
  • The static keyword is used to declare static local variables.
  • Static variables are initialized only once.
  • Static variables are useful for counters, running totals, and ID generation.
  • Variable functions allow you to call functions using variables.
  • A variable function uses the function name stored in a variable.
  • Variable functions can make dynamic function selection possible.
  • function_exists() checks whether a function is defined before calling it.
  • Always validate dynamically selected function names when they come from external input.

Frequently Asked Questions (FAQs)

1. What is a static variable in PHP?

A static variable is a local variable that retains its value between function calls instead of being initialized again every time the function runs.

2. How do you declare a static variable in PHP?

Use the static keyword before the variable declaration.

static $count = 0;

3. What is the difference between a local variable and a static variable in PHP?

A normal local variable is created when the function runs and does not retain its value after the function finishes. A static local variable retains its value between function calls.

4. What are variable functions in PHP?

Variable functions allow you to call a function by storing its name in a variable and adding parentheses to that variable.

5. How do you call a function using a variable in PHP?

Store the function name in a variable and call it using parentheses.

$functionName = "welcomeMessage";
$functionName();

6. Can variable functions accept arguments?

Yes. Variable functions can accept arguments just like normal functions.

$functionName = "addition";
echo $functionName(10, 20);

7. What is the use of function_exists() in PHP?

function_exists() checks whether a function has been defined before calling it. It returns true if the function exists and false otherwise.

8. Can static variables be used inside functions?

Yes. Static variables are commonly declared inside functions when a value needs to be retained between function calls.

9. Are variable functions and anonymous functions the same?

No. Variable functions call named functions using a variable containing the function name. Anonymous functions are functions without a regular declared name and can be stored in variables.

10. Where are static variables and variable functions useful?

Static variables are useful for counters, running totals, and tracking function calls. Variable functions are useful when selecting and executing different functions dynamically.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top