PHP Variables Scope

In PHP, variables can be declared anywhere within the script. The scope of a variable defines the section of the script where the variable can be accessed or used.

Tutorials dojo strip

PHP has three main types of variable scope:

  1. Local
  2. Global
  3. Static

Global and Local Scope

A variable declared outside any function has a global scope and can only be accessed outside functions.

Example: Variable with global scope

PHP

A variable declared within a function has a local scope and can only be accessed within that function.

Example: Variable with local scope

PHP

Local variables with the same name can be used in different functions without conflict, as they are only recognized within their respective functions.

The global Keyword

The global keyword allows you to access a global variable from within a function. To achieve this, use the global keyword before the variable names inside the function.

Example: Using the global keyword

PHP

PHP also stores all global variables in an array called $GLOBALS[index], where the index holds the variable name. This array can be accessed from within functions and used to modify global variables directly.

Example: Using $GLOBALS array

PHP

The static Keyword

Typically, when a function finishes executing, all its variables are deleted. However, sometimes we need a local variable to retain its value even after the function has completed. In such cases, we use the static keyword when declaring the variable.

Example: Using the static keyword

PHP

In this example, each time the function is called, the variable $sales retains the value it had from the previous call.

Tutorials dojo strip