PHP

PHP Variables Scope. Global vs Local
14.01.2022
img

In PHP, variables can be declared anywhere in the script.
The scope of a variable is the part of the script where the variable can be referenced/used. The scope is simply lifetime of a variable. It is block of code under which a variable is applicable or alive.
PHP has three different variable scopes:

  • local
  • global
  • static

A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside a function.

A variable declared within a function has a LOCAL SCOPE and can only be accessed within that function.

Advantages of using Global variables:
  1. You can access the global variable from all the functions or modules in a program
  2. You only require to declare global variable single time outside the modules.
  3. It is ideally used for storing “constants” as it helps you keep the consistency.
  4. A Global variable is useful when multiple functions are accessing the same data.
Advantages of using Local Variables:
  1. The use of local variables offer a guarantee that the values of variables will remain intact while the task is running
  2. If several tasks change a single variable that is running simultaneously, then the result may be unpredictable. But declaring it as local variable solves this issue as each task will create its own instance of the local variable.
  3. You can give local variables the same name in different functions because they are only recognized by the function they are declared in.
  4. Local variables are deleted as soon as any function is over and release the memory space which it occupies.

back to all posts