php global variable modifier not working

kanji picture kanji · Apr 18, 2009 · Viewed 11.7k times · Source

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?

Answer

Remy Vanherweghem picture Remy Vanherweghem · Apr 13, 2014

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;