Lesson 29 of 50 – PHP Variable Scope
58%

PHP Variable Scope

Variable scope determines where a variable can be accessed in a PHP program. Understanding scope helps you write organized functions and avoid unexpected variable behavior.

1. What Is Variable Scope?

PHP variables can have different scopes. The main categories covered in this lesson are local, global, and static variables.

Example:

<?php
$name = "Rahul";

function showName() {
    $student = "Amit";
    echo $student;
}

showName();

echo "<br>";
echo $name;
?>
Output:
Amit
Rahul

The variable $name is defined outside the function, while $student is defined inside it. Their scopes are different.

2. Local Scope

A variable declared inside a function normally has local scope. It can be accessed within that function, but not directly outside it.

<?php
function displayMessage() {
    $message = "Welcome to PHP";
    echo $message;
}

displayMessage();
?>
Output:
Welcome to PHP

Example of a local variable:

<?php
function calculateSum() {
    $a = 10;
    $b = 20;

    echo $a + $b;
}

calculateSum();
?>
Output:
30

The variables $a and $b are local to calculateSum().

3. Accessing a Local Variable Outside a Function

A local variable cannot normally be accessed directly outside the function in which it is declared.

<?php
function showAge() {
    $age = 20;
    echo $age;
}

showAge();

echo "<br>";

// This variable is not defined in the outer scope.
// echo $age;
?>
Output:
20

The commented line is not executed. If you uncomment it, PHP will report an undefined variable warning because $age is not defined in the outer scope.

To make a value available outside a function, you can return it and store the result in another variable.

<?php
function getAge() {
    $age = 20;
    return $age;
}

$studentAge = getAge();

echo $studentAge;
?>
Output:
20
4. Global Scope

A variable declared outside a function has global scope. It is not automatically available inside a function.

<?php
$course = "PHP";

function showCourse() {
    // $course is not automatically available here.
    echo "Learning programming";
}

showCourse();

echo "<br>";
echo $course;
?>
Output:
Learning programming
PHP

The function can access the global variable only through an appropriate method, such as the global keyword or the $GLOBALS array.

5. Using the global Keyword

The global keyword allows a function to access a variable from the global scope.

<?php
$number = 100;

function showNumber() {
    global $number;
    echo $number;
}

showNumber();
?>
Output:
100

Example: Modify a global variable

<?php
$count = 10;

function increaseCount() {
    global $count;
    $count = $count + 5;
}

increaseCount();

echo $count;
?>
Output:
15

The function changes the global variable because it declares global $count;. Use global variables carefully because they create dependencies between different parts of a program.

6. Using the $GLOBALS Array

PHP provides the $GLOBALS superglobal array for accessing global variables from different parts of a script, including inside functions.

<?php
$price = 500;

function showPrice() {
    echo $GLOBALS['price'];
}

showPrice();
?>
Output:
500

Example: Update a global variable

<?php
$total = 100;

function addAmount() {
    $GLOBALS['total'] += 50;
}

addAmount();

echo $total;
?>
Output:
150

The $GLOBALS array contains references to variables in the global scope. The array keys are the global variable names.

7. Static Variables

A local variable normally starts again when a function is called. A variable declared with static retains its value between calls to that function.

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

    $count++;

    echo $count . "<br>";
}

counter();
counter();
counter();
?>
Output:
1
2
3

The variable $count is local to the function but retains its value between calls. It is initialized only once for that function execution context.

Without static:

<?php
function normalCounter() {
    $count = 0;
    $count++;

    echo $count . "<br>";
}

normalCounter();
normalCounter();
normalCounter();
?>
Output:
1
1
1
8. Function Parameters and Scope

Function parameters are local variables. They receive values when the function is called and can be used inside that function.

<?php
function calculateSquare($number) {
    return $number * $number;
}

$result = calculateSquare(6);

echo $result;
?>
Output:
36

The parameter $number belongs to calculateSquare(). The variable $result is defined in the outer scope.

Example: Separate local variables

<?php
function firstFunction() {
    $message = "Hello";
    echo $message . "<br>";
}

function secondFunction() {
    $message = "Welcome";
    echo $message;
}

firstFunction();
secondFunction();
?>
Output:
Hello
Welcome

Both functions have a local variable named $message. They do not share the same local variable because each function has its own scope.

9. Practical Example: Student Fee Calculator

This example demonstrates local variables, function parameters, return values, and the use of separate functions without relying on global variables.

<?php
function calculateFee($monthlyFee, $months) {
    $totalFee = $monthlyFee * $months;

    return $totalFee;
}

function calculateBalance($totalFee, $paidFee) {
    return $totalFee - $paidFee;
}

$studentName = "Rahul";
$monthlyFee = 1000;
$months = 6;
$paidFee = 4000;

$totalFee = calculateFee($monthlyFee, $months);
$balance = calculateBalance($totalFee, $paidFee);

echo "Student: " . $studentName . "<br>";
echo "Total Fee: Rs. " . $totalFee . "<br>";
echo "Paid Fee: Rs. " . $paidFee . "<br>";
echo "Pending Fee: Rs. " . $balance;
?>
Output:
Student: Rahul
Total Fee: Rs. 6000
Paid Fee: Rs. 4000
Pending Fee: Rs. 2000

The functions use their own local variables and receive information through parameters. Their return values are stored in variables outside the functions.

Practice Assignments
  1. Create a function with a local variable and display its value.
  2. Create a global variable and access it using the global keyword.
  3. Update a global variable using the $GLOBALS array.
  4. Create a counter function using a static variable.
  5. Call a function three times and compare local and static variables.
  6. Create two functions with local variables having the same name.
  7. Return a local variable from a function and display it outside.
  8. Create a function that calculates a student's total fee using parameters.
  9. Create a fee calculator that returns the pending balance without using global variables.

🧠 Quick Quiz

1. Where is a local variable normally accessible?




2. Which keyword allows a function to access a global variable?




3. What is the purpose of a static local variable?