17

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?

3
  • 1
    Is this the exact code? Are you leaving any information out here? Commented Apr 18, 2009 at 21:53
  • of course he has - like what exact version of PHP...? Commented Apr 19, 2009 at 11:23
  • See 3v4l.org/IsvLd for a reproducible version of the issue. Commented Feb 19, 2020 at 20:51

6 Answers 6

31

I was also faced with your problem. As I am using a framework (Yii), I wasn't exactly aware that my code was indeed nested inside functions and, therefore, global wasn't behaving as expected (as explained by omadmedia and others).

My solution is pretty simple:

global $a;
global $b;
$a = 1;
$b = 2;

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

    $b = $a + $b;
} 

Sum();
echo "***: ".$b;
Sign up to request clarification or add additional context in comments.

3 Comments

Works for Laravel as well!
This also works for the PsySH REPL console and the Jupyter-PHP kernel
I had exactly the same problem but inside a class with global vars at the top and neasted functions. However, I was able to access those globals inside neasted functions through object's $this->myglobalvar.
18

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.

Comments

8

As @AgelessEssence answered, global keyword doesn't work if you have a nested function. It is obvious in his example. However, if it is not clear if a file is included. Here is the example.

//a.php
function f() {
    require_once('./a_inc.php');
}

f();

//a_inc.php
$a = 12;

function g() {
    global $a;

    var_dump($a);
}

g();

//result
null

In the code above, $a looks like a global variable. Actually, it is not because it is included in the function f() in a.php and $a is part of function f().

So, when your global keyword doesn't work, check whether it is included in a function. As the solution for this problem well explained in other answers, so I didn't add it here.

Comments

3

i have the SAME PROBLEM like you, and finally found the answer

working code / DEMO

$a=1;

function showA() {

    global $a;
    var_export($a);  

} 

showA(); // outputs "1"

non working code / DEMO

function encapsulation() {

    $a=1;

    function showA() {

        global $a;
        var_export($a);  

    };

    showA();

}  

encapsulation(); // outputs "NULL"

as you can see, the problem occurs when using the global keyword inside a nested function definition

More Info: php.net/manual/en/language.variables.scope.php#92868

2 Comments

What would be the best workaround to this? Since this is exactly what I need. (What i think I need)
Same. I introduced this problem when adding a lambda wich would require modules. Since then i wouldnt been able to use global variables on the required file. what worked for me was defining explicitly global variables.
2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.