hohner hohner - 5 years ago 210
PHP Question

Declaring a global variable inside a function

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?

Answer Source

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

$ref_id = 1;

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

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

felix

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download