在函数内声明一个全局变量 [英] Declaring a global variable inside a function

查看:111
本文介绍了在函数内声明一个全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个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.

我遇到的问题是,当 grabReferral()的时候,调用 processJoin.php 中的 c>函数, $ 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?

推荐答案

你必须在第二个函数中定义全局var。

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

这篇关于在函数内声明一个全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆