在函数内声明全局变量
我有两个 PHP 文件.首先,我根据 $_GET
值设置了一个 cookie,然后调用一个函数,然后将该值发送到另一个文件.这是我在 join.php 中使用的一些代码:
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"]);
然后另一个文件 (processJoin.php) 会将此值(以及其他)发送到其他文件,这些文件将处理数据并将其插入到数据库中.
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.
我遇到的问题是,当 processJoin.php 中的 grabReferral()
函数被调用时,$referralID
变量是没有在全球范围内定义 - processJoin.php
中的其他函数似乎无法访问它以发送到其他文件/进程.
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.
我在 processJoin.php 中试过这个:
grabReferral($rid) {
global $ref_id;
$ref_id = $rid;
}
someOtherFunction() {
sendValue($ref_id);
}
但是 someOtherFunction 似乎无法访问或使用 $ref_id
值.我也试过使用 define()
无济于事.我做错了什么?
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?
推荐答案
你也必须在第二个函数中定义全局变量..
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);
}
菲利克斯
相关文章