Variable Scope and Global Variables in PHP Practice Questions with Solutions

Introduction

Variable scope determines where a variable can be accessed and used in PHP. A variable declared inside a function is generally local, while a variable declared outside a function has global scope. PHP also provides the global keyword, $GLOBALS array, and static keyword to work with variables in different situations. Variable Scope and Global Variables in PHP Practice Questions with Solutions to help you to understand the concepts.

Question 1: Create and Access a Local Variable

Problem Statement:
Create a function named showStudent() that declares a local variable $name and displays the student’s name.

PHP Solution:

<?php
function showStudent() {
    $name = "Rahul";

    echo "Student Name: " . $name;
}

showStudent();
?>

Sample Output:

Student Name: Rahul

Explanation:

  • $name is declared inside the function.
  • It is a local variable because it belongs to showStudent().
  • The variable can be accessed inside the function.
  • The function displays its value when called.

Concepts Covered:

  • Local variables
  • Function scope
  • Accessing local variables

Question 2: Understand Global Variable Scope

Problem Statement:
Create a variable named $institute outside a function. Create another function named showInstitute() and try to display the global variable directly. Then display it outside the function.

PHP Solution:

<?php
$institute = "VSIT Coding Institute";

function showInstitute() {
    echo "Inside Function: ";

    var_dump(isset($institute));
}

showInstitute();

echo "Outside Function: " . $institute;
?>

Sample Output:

Inside Function: bool(false)
Outside Function: VSIT Coding Institute

Explanation:

  • $institute is declared outside the function, so it has global scope.
  • A global variable cannot be accessed directly inside a function.
  • isset() checks whether the variable is available in the current scope.
  • Outside the function, the variable can be accessed normally.

Concepts Covered:

  • Global variables
  • Local and global scope
  • isset() function

Question 3: Access a Global Variable Using the global Keyword

Problem Statement:
Create a global variable named $company. Use the global keyword inside a function named showCompany() to display its value.

PHP Solution:

<?php
$company = "Tech Solutions";

function showCompany() {
    global $company;

    echo "Company Name: " . $company;
}

showCompany();
?>

Sample Output:

Company Name: Tech Solutions

Explanation:

  • $company is declared outside the function.
  • The global keyword makes the global variable available inside the function.
  • The function can now access and display its value.

Concepts Covered:

  • Global keyword
  • Accessing global variables
  • Function scope

Question 4: Modify a Global Variable Inside a Function

Problem Statement:
Create a global variable named $salary with an initial value of 30,000. Create a function named increaseSalary() that increases the salary by 5,000 using the global keyword.

PHP Solution:

<?php
$salary = 30000;

function increaseSalary() {
    global $salary;

    $salary = $salary + 5000;
}

increaseSalary();

echo "Updated Salary: " . $salary;
?>

Sample Output:

Updated Salary: 35000

Explanation:

  • $salary is a global variable.
  • The global keyword allows the function to access the original variable.
  • The function increases its value by 5,000.
  • The updated value is available outside the function.

Concepts Covered:

  • Modifying global variables
  • global keyword
  • Variable scope

Question 5: Use the $GLOBALS Array

Problem Statement:
Create two global variables named $basicSalary and $allowance. Use the $GLOBALS array inside a function named calculateSalary() to calculate and return the total salary.

PHP Solution:

<?php
$basicSalary = 30000;
$allowance = 5000;

function calculateSalary() {
    $total = $GLOBALS["basicSalary"] + $GLOBALS["allowance"];

    return $total;
}

echo "Total Salary: " . calculateSalary();
?>

Sample Output:

Total Salary: 35000

Explanation:

  • $GLOBALS is a PHP superglobal array.
  • It provides access to global variables from different scopes.
  • $GLOBALS["basicSalary"] accesses the basic salary.
  • $GLOBALS["allowance"] accesses the allowance.
  • The function adds both values and returns the result.

Concepts Covered:

  • $GLOBALS array
  • Superglobal variables
  • Accessing global values
  • Returning results

Question 6: Understand Local and Global Variables with the Same Name

Problem Statement:
Create a global variable named $message with the value Welcome to PHP. Inside a function named showMessage(), create another local variable with the same name and display both values.

PHP Solution:

<?php
$message = "Welcome to PHP";

function showMessage() {
    $message = "Learning PHP Functions";

    echo "Local Message: " . $message . "\n";
}

showMessage();

echo "Global Message: " . $message;
?>

Sample Output:

Local Message: Learning PHP Functions
Global Message: Welcome to PHP

Explanation:

  • The global $message is declared outside the function.
  • A separate local $message is created inside the function.
  • Both variables have the same name but belong to different scopes.
  • Changing the local variable does not change the global variable.

Concepts Covered:

  • Local variables
  • Global variables
  • Same variable names
  • Variable scope separation

Question 7: Use Multiple Global Variables in a Function

Problem Statement:
Create three global variables named $basic, $hra, and $da. Use the global keyword inside a function named calculateGrossSalary() to calculate the gross salary.

PHP Solution:

<?php
$basic = 25000;
$hra = 5000;
$da = 3000;

function calculateGrossSalary() {
    global $basic, $hra, $da;

    $grossSalary = $basic + $hra + $da;

    return $grossSalary;
}

echo "Gross Salary: " . calculateGrossSalary();
?>

Sample Output:

Gross Salary: 33000

Explanation:

  • Three global variables store salary components.
  • The global keyword makes all three variables available inside the function.
  • The function adds basic salary, HRA, and DA.
  • The calculated gross salary is returned.

Concepts Covered:

  • Multiple global variables
  • Global keyword
  • Salary calculations
  • Returning values

Question 8: Use 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 has been called.

PHP Solution:

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

    $count++;

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

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

Sample Output:

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

Explanation:

  • $count is declared using the static keyword.
  • A static local variable retains its value between function calls.
  • It is initialized only once.
  • Each function call increases the existing value by one.

Concepts Covered:

  • Static variables
  • Local variable scope
  • Retaining values between function calls

Question 9: Create a Global Counter Using $GLOBALS

Problem Statement:
Create a global variable named $totalOrders with an initial value of zero. Create a function named addOrder() that increases the global counter each time it is called using $GLOBALS.

PHP Solution:

<?php
$totalOrders = 0;

function addOrder() {
    $GLOBALS["totalOrders"]++;
}

addOrder();
addOrder();
addOrder();

echo "Total Orders: " . $totalOrders;
?>

Sample Output:

Total Orders: 3

Explanation:

  • $totalOrders is declared outside the function.
  • $GLOBALS["totalOrders"] accesses the global variable.
  • Every function call increases the counter by one.
  • The updated count can be accessed outside the function.

Concepts Covered:

  • $GLOBALS array
  • Updating global variables
  • Global counters
  • Function calls

Question 10: Build an Employee Salary Calculator Using Global Variables

Problem Statement:
Create global variables for basic salary, HRA, DA, and PF. Create a function named calculateNetSalary() that accesses these variables using the global keyword and calculates the employee’s net salary.

PHP Solution:

<?php
$basicSalary = 30000;
$hra = 5000;
$da = 3000;
$pf = 2000;

function calculateNetSalary() {
    global $basicSalary, $hra, $da, $pf;

    $grossSalary = $basicSalary + $hra + $da;

    $netSalary = $grossSalary - $pf;

    return $netSalary;
}

echo "Basic Salary: " . $basicSalary . "\n";
echo "HRA: " . $hra . "\n";
echo "DA: " . $da . "\n";
echo "PF: " . $pf . "\n";
echo "Net Salary: " . calculateNetSalary();
?>

Sample Output:

Basic Salary: 30000
HRA: 5000
DA: 3000
PF: 2000
Net Salary: 36000

Explanation:

  • All salary variables are declared outside the function.
  • The global keyword makes them accessible inside the function.
  • Gross salary is calculated by adding basic salary, HRA, and DA.
  • PF is subtracted from gross salary.
  • The function returns the final net salary.

Concepts Covered:

  • Global variables
  • Multiple global parameters
  • Salary calculations
  • Return statement
  • Function scope

Key Takeaways

  • Variable scope determines where a variable can be accessed.
  • Variables declared inside functions are generally local variables.
  • Variables declared outside functions have global scope.
  • Global variables cannot be accessed directly inside PHP functions.
  • The global keyword allows functions to access global variables.
  • The $GLOBALS array provides another way to access and modify global variables.
  • Local and global variables can have the same name without being the same variable.
  • Static variables retain their values between function calls.
  • Use local variables and function parameters when possible to keep code easier to understand and maintain.

Frequently Asked Questions (FAQs)

1. What is variable scope in PHP?

Variable scope defines where a variable can be accessed and used in a PHP program.

2. What is a local variable in PHP?

A local variable is declared inside a function and can normally be accessed only within that function.

3. What is a global variable in PHP?

A global variable is declared outside a function. It can be accessed in the global scope and made available inside functions using global or $GLOBALS.

4. Can we access a global variable directly inside a PHP function?

No. A global variable is not automatically available inside a function. You must use the global keyword or $GLOBALS array.

5. What is the use of the global keyword in PHP?

The global keyword allows a function to access and modify variables declared in the global scope.

6. What is the $GLOBALS array in PHP?

$GLOBALS is a superglobal associative array that provides access to variables in the global scope from different parts of a PHP program.

7. What is the difference between global and static variables?

Global variables are declared outside functions and belong to the global scope. Static variables are declared inside functions and retain their values between function calls.

8. Can local and global variables have the same name?

Yes. A local variable and a global variable can have the same name because they belong to different scopes.

9. What happens to a local variable after a function finishes?

A normal local variable is no longer available after the function finishes executing.

10. Why should we avoid using too many global variables?

Too many global variables can make code difficult to understand, test, and maintain. Passing values through function parameters is often a cleaner approach.

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

Scroll to Top