changing a global variable value in php

Im Learining php and I'm Just confused with some teaches of w3schools!

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

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

myTest();
echo $y; // outputs 15
?>

in this code it say's that the output will be 15 because we get the "y" variable value in myTest function! but how php does know that the "y" variable in $y = $x + $y; is the global one or new one ?!

Upvotes: 1

Views: 2070

Answers (2)

Abhay Maurya
Abhay Maurya

Reputation: 12277

$y is global one inside myTest() function as you have declared:

global $x, $y;

so inside myTest() :

global $x, $y;//$x=5 and $y=10
$y = $x+$y; // value of $y will be over written by (10+5) and it will become 15

Just to clear your confusion more:

function myTest() {
   $y = 200; //local $y
   echo $y; //200
   global $x, $y;//now global $y will overwrite local $y
   $y = $x + $y;
   echo $y; //15
}

Upvotes: 1

CGriffin
CGriffin

Reputation: 1476

The global $y and the $y resulting from $y = $x + $y are the same variable. global doesn't define a different variable, it defines the 'scope' of the variable, ie, where it can be accessed within the script. So $y = $x + $y changes the value of the global variable.

If, for example, you rewrote the function like this:

function myTest() {
    $x, $y;
}

$x and $y would be different from the previously-defined variables because you did not define them as global.

Upvotes: 3

Related Questions