0

If a variable is defined outside a function and again it defined inside the function then why the value of variable is not changed after calling the function.

$a = 12;

Function abc()
{
    $a=15; 
    echo $a;
}

abc(); 
echo $a;

OUTPUT:

1512

Why not:

1515
treyBake
  • 6,440
  • 6
  • 26
  • 57
Deepak Kishore
  • 128
  • 1
  • 9

2 Answers2

1

You should use global keyword ( or sometimes $GLOBALS['a'] )

http://php.net/manual/en/language.variables.scope.php

$a=12;

function abc(){
    global $a;
    $a=15; 
    echo $a;
}

abc(); 
echo $a;
shawn
  • 4,305
  • 1
  • 17
  • 25
1

Because variable scope is limit to function body, you can make the variable global if you want to use the above variable like:

function abc() {
   global $a;
}
Shahbaz A.
  • 4,047
  • 4
  • 34
  • 55