Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a global variable inside a function

Tags:

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?

like image 843
hohner Avatar asked Mar 18 '11 17:03

hohner


People also ask

Can we declare global variable inside a function?

Global variables can be used by everyone, both inside of functions and outside.

Can I declare a global variable inside a function in Python?

Yes, but why? just do, global something , it will create a new global variable if it doesn't exist.

How do you bring a global variable to a function?

Using the “global” Keyword. To globalize a variable, use the global keyword within a function's definition. Now changes to the variable value will be preserved.

Can you declare a global variable in a function in C?

The C compiler recognizes a variable as global, as opposed to local, because its declaration is located outside the scope of any of the functions making up the program. Of course, a global variable can only be used in an executable statement after it has been declared.


2 Answers

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

like image 114
Felix Geenen Avatar answered Oct 03 '22 13:10

Felix Geenen


personally, I would recommend the $GLOBALS super variable.

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

DEMO

like image 33
Brad Christie Avatar answered Oct 03 '22 14:10

Brad Christie