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?
Global variables can be used by everyone, both inside of functions and outside.
Yes, but why? just do, global something , it will create a new global variable if it doesn't exist.
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.
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.
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
personally, I would recommend the $GLOBALS
super variable.
function foo(){ $GLOBALS['foobar'] = 'foobar'; } function bar(){ echo $GLOBALS['foobar']; } foo(); bar();
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With