PHP Variable Scope

- April 10, 2024

PHP variables can be defined anywhere. but in PHP some type of variable scope

There are 3 types of variable scope:

  1. Global
  2. Local
  3. Static

Global: when declaring a variable out of a function it automatically behaves global variable. it’s can

  • It can be accessed from anywhere
  • can be accessed in function when defined out of function

Example:

$x = " i am global";

function myFun(){
echo "Print value inside function $x ";
}

echo "Print value out of Function: $x ";

// result: Print value out of Function: I am global

Note: under double quotation, we can use php variables, but we can’t write a variable under single quotation

Local: local variables are the opposite of global. when a variable is defined under a function then it’s local, this variable can’t be used out of function.

  • can’t access out of function
  • only access under the function

Example

$x = " i am global";

function myFun(){
echo "Print value inside function $x ";
}

echo "Print value out of Function: $x ";

// result: Print value out of Function: I am global

PHP global keyword

When you need an access a local variable outside of the function then you can use the global keyword

Example:

$x = 5;
$y = 20;

function myFunc(){
global $x, $y; // make it global
$y = $x + $y;
}

echo $y; // 25

Note: PHP also stores all global variables in an array called $GLOBALS[index]. All the super global variables are stored in it. remember it!

PHP The static Keyword

normally when the function is finished/executed the variables are deleted from memory. but sometimes we need to store the variable for some task.

in this situation, we will use static keyword

Example:

function myFunc(){
static $x = 0;
echo $x;
$x++; //increment the x
}

myFunc(); // 0
myFunc(); // 1
myFunc(); // 2

Related Posts

Leave Us a Comment