Rohit Kumar Rohit Kumar - 5 months ago 17
PHP Question

PHP Variable Scope understanding

Just started learning PHP, and while experimenting with variable scopes, I created this code:

<?php
$x = 5;

function scopeTest($x) {
global $x;
echo $x;
}

scopeTest(4);
?>


In the given function I pass value
4
, in the function that value is stored in variable
$x
(local to the function). The output of this code is
5
and not
4
.

I don't know where the variable with value
4
gone? I know I can do this by changing the local variable name in the function but I want to know flow of this program, how it is outputting
5
.

Is the local variable
$x
overridden with the global variable
$x
?

Is there any way to access the local variable
$x
value
4
within the function?

Answer

The local variable is being overwritten with the statement global and since they are sharing the same variable name, you lost reference to it.

But by doing this, you can use both:

$x = 5;

function scopeTest($x) {
  echo $GLOBALS['x'];
  echo $x;            
}

scopeTest(4);

Or.. just rename the variable

function scopeTest($y) {
  global $x;
  echo $x, $y;           
}
Comments