views:

1129

answers:

5

I'm using the basic php example for the global modifier, and it doesn't work for me :-|

$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo "***: ".$b;

Here is the result... $ ***: 2

Is there any parameter on the php.ini that might effect this?

+1  A: 

This works for me, I never tweaked any php.ini parameter.

Ilya Birman
+1  A: 

Working fine for me as well. This is an exact copy of the code?

Hawker
I get 3 as well.
DGM
This should have been a comment, to the reply by Ilya or the question.
OIS
+1  A: 

Your example code above works for me. But you can also use the $GLOBALS supervariable.

function Sum()
{
    $a = $GLOBALS["a"];
    $b =& $GLOBALS["b"];
    $b = $a + $b;
}

Global variables should not be used if you can help it though. There are better ways to make your functions. Use parameters (arguments) (maybe pass by reference) and return a value instead.

/**
 * Calculate the sum of the parameters
 * @param int|float $a one or more parameter
 * @param int|float $a, ... 
 * @return int|float
 */
function sum($a)
{
    $args = func_get_args();
    return array_sum($args);
}

$a = 1;
$b = 2;

$b = sum($a, $b);

With PHPDOC you can understand what your functions do years from now without reading the code. With a good IDE you can also get the explanation and argument order as you write the function.

OIS
A: 

The only thing I could imagine going wrong is if you're assigning variables in the global scope after calling a function first. That is, your function is actually declaring the variables and then you just overwrite them elsewhere. For example, calling Sum() and then doing $a=1, $b=2.

Christopher Nadeau
+1  A: 

Believe it or not, I get answer: 2 as well. This means there are indeed some cases where global is not working.

Tried finding the cause: It seems that if you have a function and put the OP's code (which is a php.net example) inside that function, you will get answer 2. This is a bit weird and kinda makes sense in a way...

(I'm using PHP 5.2.5 under Apache 2.2.8 in Win XP)

LE: MY SOLUTION OK, solved this: when you use global in the 2nd function you obviously get the superglobal variables, those available to everybody (ie. decalared outside any function), but since $a and $b are declared inside the 1st function, they are not part of that scope and are not available to the 2nd function. My guess for a solution is to declare $a and $b global, outside the 2nd function as well, that is inside the 1st function. !! Note that the 1st may be not so obvious due to various reasons, like your file (only containing the 2nd function) being included somewhere in the body of a different function in a different file.

omadmedia