What are scopes of variable in php?

Last updated 1 year, 9 months ago | 230 views 75     5

scopes of variable

Scopes define visibility of a variables. 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 used.

There are three scopes available in php

  1. global
  2. local
  3. static
 

global

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

we can use global variable within a function by using "global" keyword.

<?php
$x = 25;
$y = 10;

function test() {
    global $x, $y;
    $y = $x + $y;
}

test();
echo $y; 
?>

// outputs will be 35

local

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

static

Normally, when a function is executed, all of its variables are deleted. However, sometimes we want a local variable NOT to be deleted. We need it for a further job.

To do this, use the static keyword when you first declare the variable.