๐ŸŽ“ A1Learner
๐Ÿ”

PHP Variable Scope

Variable scope is the part of a program where a variable can be used. Each function has its own scope for the variables made inside it.

A wall between scopes

The outside $city holds Oslo. The function makes its own $city with Bergen, and that local value prints inside the call.

<?php
$city = "Oslo";

function showCity() {
  $city = "Bergen";
  echo $city . "\n";
}

showCity();
echo $city . "\n";

Reaching out with global

The word global links the name $count inside bump to the outside $count. The function adds 1, and the new value prints after the call.

<?php
$count = 0;

function bump() {
  global $count;
  $count = $count + 1;
}

bump();
echo $count . "\n";

A static variable remembers

The static variable $n is set up on the first call only. Each call adds 1 and prints the kept value.

<?php
function counter() {
  static $n = 0;
  $n = $n + 1;
  echo $n . "\n";
}

counter();
counter();

Example

<?php
$theme = "light";

function useDark() {
  global $theme;
  $theme = "dark";
}

echo $theme . "\n";
useDark();
echo $theme . "\n";

Key points

  • A variable made inside a function lives only inside that function.
  • A variable inside a function is separate from an outside variable with the same name.
  • The global keyword links a name inside a function to the outside variable of that name.
  • A change made through global changes the outside variable.
  • A static variable keeps its value between calls to its function.
  • A static variable is set up only on the first call.

In this example, the outside variable $theme starts as light. The first print shows light. useDark links its $theme to the outside one with global and changes it to dark, so the last print shows dark.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz PHP Compiler

Exercise

What does the static word do to a variable inside a function?