22

I have two PHP files. In the first I set a cookie based on a $_GET value, and then call a function which then sends this value on to the other file. This is some code which I'm using in join.php:

include('inc/processJoin.php');
setcookie("site_Referral", $_GET['rid'], time()+10000);
$joinProc = new processJoin();
$joinProc->grabReferral($_COOKIE["site_Referral"]);

The other file (processJoin.php) will then send this value (among others) to further files which will process and insert the data into the database.

The problem I'm having is that when the grabReferral() function in processJoin.php is called, the $referralID variable isn't being defined on a global scale - other functions in processJoin.php can't seem to access it to send to other files/processes.

I've tried this in processJoin.php:

grabReferral($rid) {
   global $ref_id;
   $ref_id = $rid;
}

someOtherFunction() {
   sendValue($ref_id);
}

But the someOtherFunction can't seem to access or use the $ref_id value. I've also tried using define() to no avail. What am I doing wrong?

hohner
  • 10,920
  • 8
  • 45
  • 83
  • 3
    Why oh why are you using global variables? There is almost always a better solution. – Matt Ball Mar 18 '11 at 17:26
  • 3
    *(should read)* [Global in Functions](http://stackoverflow.com/questions/5166087/php-global-in-functions/5166527#5166527) – Gordon Mar 18 '11 at 17:28
  • @MattBall: Agreed. And, based on variable name, I would venture to say `define('REF_ID',$id);` and `if(defined('REF_ID'))...` are a better solution. – Brad Christie Mar 18 '11 at 17:29
  • 2
    @Brad no, it wouldnt. Avoid the global scope. – Gordon Mar 18 '11 at 17:32
  • @BradChristie When I use `define('REF_ID',$rid)` in the `grabReferral()` function, I can't access the constant in the `someotherFunction()` function. Any more ideas? – hohner Mar 18 '11 at 17:35
  • @Jamie: See the [answer I posted](http://stackoverflow.com/questions/5355644/declaring-a-global-variable-inside-a-function/5355680#5355680) and use `$GLOBALS` instead (but avoid it if you can). – Brad Christie Mar 18 '11 at 17:36

7 Answers7

36

you have to define the global var in the second function as well..

// global scope
$ref_id = 1;

grabReferral($rid){
   global $ref_id;
   $ref_id = $rid;
}

someOtherFunction(){
    global $ref_id;
    sendValue($ref_id);
}

felix

Felix Geenen
  • 1,652
  • 1
  • 20
  • 26
24

personally, I would recommend the $GLOBALS super variable.

function foo(){
  $GLOBALS['foobar'] = 'foobar';
}
function bar(){
  echo $GLOBALS['foobar'];
}
foo();
bar();

DEMO

Brad Christie
  • 96,086
  • 15
  • 143
  • 191
12

This is a simple and working code to initialize global variable from a function :

function doit()
{
    $GLOBALS['val'] = 'bar';
}
doit();
echo $val;

Gives the output as :

bar
Vinay Jeurkar
  • 2,994
  • 9
  • 34
  • 55
3

The following works.

<?php

    foo();
    bar();

    function foo()
    {
        global $jabberwocky;
        $jabberwocky="Jabberwocky<br>";

        bar();
    }

    function bar()
    {
        global $jabberwocky;
        echo $jabberwocky;
    }

?>

to produce:

Jabberwocky
Jabberwocky

So it seems that a variable first declared as global inside a function and then initalised inside that function acquires global scope.

Oliver Olding
  • 41
  • 1
  • 8
Leo smith
  • 102
  • 4
2

The global keyword lets you access a global variable, not create one. Global variables are the ones created in the outermost scope (i.e. not inside a function or class), and are not accessible inside function unless you declare them with global.

Matteo Riva
  • 23,656
  • 11
  • 69
  • 103
1

Disclaimer: none of this code was tested, but it definitely gets the point across.

Choose a name for the variable you want to be available in the global scope. Within the function, assign a value to the name index of the $GLOBALS array.

function my_function(){

    //...

    $GLOBALS['myGlobalVariable'] = 42;    //globalize variable

    //...
}

Now when you want to access the variable from code running in the global scope, i.e. NOT within a function, you can simply use $ name to access it, without referencing the $GLOBALS array.

<?php
    //<global scope>

    echo $myGlobalVariable;  //outputs "42"

    //</global scope>
?>

To access your global variable from a non-global scope such as a function or an object, you have two options:

  1. Access it through the appropriate index of the $GLOBALS array. Ex: $GLOBALS['myGlobalVariable'] This takes a long time to type, especially if you need to use the global variable multiple times in your non-global scope.
  2. A more concise way is to import your global variable into the local scope by using the 'global' statement. After using this statement, you can reference the global variable as though it were a local variable. Changes you make to the variable will be reflected globally.

        //<non global scopes>
        function a(){
            //...
            global $myGlobalVariable;
            echo $myGlobalVariable;    // outputs "42"
            //...
         }
        function b(){
            //...
            echo $GLOBALS['myGlobalVariable'];    // outputs "42"
            echo $myGlobalVariable;               // outputs "" (nothing)
                                                  // ^also generates warning - variable not defined
            //...             
        }
        //</non global scopes>
    

Please use global variables in any language with caution, especially in PHP.

See the following resources for discussion of global variables:

  • See also: [http://discuss.joelonsoftware.com/default.asp?design.4.249182.18](http://discuss.joelonsoftware.com/default.asp?design.4.249182.18) – Carl Schroedl Aug 10 '11 at 19:43
0

The visibility of a variable

I hope that helped

<?php
$a = 1;
$b = 2;

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

    $b = $a + $b;
} 

Sum();
echo $b;
?>