Using Global and Static Variables

Tutorial 4 of 5

Using Global and Static Variables in PHP: A Detailed Guide

1. Introduction

Goal

This tutorial aims to provide a comprehensive understanding of how to use global and static variables in PHP. By the end of this tutorial, you'll be able to understand the difference between local, static, and global variables and how to use them to manage state and share data across different parts of your PHP scripts effectively.

Learning Outcomes

  • Understand what global and static variables are
  • Know when and why to use global and static variables
  • Be able to declare and use global and static variables in PHP

Prerequisites

A basic understanding of PHP, including syntax and basic programming concepts, is required.

2. Step-by-Step Guide

Global Variables

Global variables in PHP are declared outside of all functions and can be accessed from any part of the script. To access a global variable inside a function, you need to use the global keyword before the variable.

Static Variables

Static variables in PHP exist only in a local function scope, but do not lose their value when the function execution is completed. To declare a static variable, use the static keyword before the variable.

3. Code Examples

Example 1: Using Global Variables

$g_var = "I am a global variable";  // This is a global variable

function test() {
    global $g_var;  // Declare the variable as global to use it inside the function
    echo $g_var;
}

test();  // Outputs: "I am a global variable"

Example 2: Using Static Variables

function countFunc() {
    static $count = 0;  // This is a static variable
    $count++;
    echo $count;
}

countFunc();  // Outputs: 1
countFunc();  // Outputs: 2

4. Summary

In this tutorial, we learned about global and static variables in PHP. Global variables can be accessed from any part of the script, while static variables exist only in a local function scope but do not lose their value when the function execution is completed.

As next steps, consider learning more about other types of variables and scopes in PHP, as well as how they can be used together with global and static variables for effective data management.

5. Practice Exercises

  1. Exercise 1: Create a script that uses a global variable to count how many times a function was called.

Solution:

```php
$count = 0;

function test() {
global $count;
$count++;
echo "The function was called $count times";
}

test();
test();
```

  1. Exercise 2: Create a function that uses a static variable to keep track of how many times it was called.

Solution:

```php
function countFunc() {
static $count = 0;
$count++;
echo "The function was called $count times";
}

countFunc();
countFunc();
```

Remember to always practice what you've learned to reinforce your understanding. Happy coding!