CodeBlanks Logo Icon CodeBlanks

Function scope

PHP course · Beginner · Lesson 74/116

Learn that variables inside a function are not visible outside.

Function scope

Variables defined inside a function are called local variables and are not visible from outside. So after function counter() { $n = 5; }, writing echo $n; outside raises an error in PHP.

This behavior is known as scope. Each function has its own scope; outer variables do not appear inside automatically. This keeps functions from mixing up each other's variables.

The global keyword

To use an outer variable inside a function, you can import it with the global keyword. Example: $score = 0; function addPoint() { global $score; $score += 1; }.

Using global does not copy the variable; the inside and outside share the same one. Still, many globals make code hard to follow; use them carefully.

Exercise Print a counter with a local variable

Define a parameterless function named showCounter. In the body, define $count = 1; and print it with echo $count . "\n";. Then call the function.

Show example solution
Write function showCounter() { $count = 1; echo $count . "\n"; }, then call with showCounter();.
Example solution:
<?php
// Define showCounter with a $count variable inside
function showCounter() {
    $count = 1;
    echo $count . "\n";
}
showCounter();

Test yourself

  1. What does the code below do?

    function show() {
        $city = "Ankara";
    }
    show();
    echo $city;
    • Prints Ankara
    • Prints show
    • Prints a blank line
    • Errors, $city is undefined
    Show answer

    Errors, $city is undefined — Correct. $city is local to the function; it is undefined outside.

  2. Complete the global declaration

    $price = 100;
    
    function showPrice() {
        ____ $price;
        echo $price;
    }
    showPrice();
    Show answer
    $price = 100;
    
    function showPrice() {
        global $price;
        echo $price;
    }
    showPrice();
  3. Match scope concepts

    Defined inside function
    Local variable
    global $n
    Reaches outer variable
    Function without return
    Returns null

All lessons in Beginner