开发者

Array not getting populated by my function

I am trying to simplify adding stuff to some arrays with a custom function in PHP.

 $campaignLimits    = array();
 $couponLimits      = array();
 $subscriptions     = array();

The function looks like this:

 function DefineSubscription($itemname,$subscription,$campaignlimit,$couponlimit)
 {
    // Make em global
    global $campaignLimits, $couponLimits, $subscriptions;

    // Add开发者_如何学编程 stuff to the arrays
    $campaignLimits[$itemname]      = $campaignlimit;
    $couponLimits[$itemname]        = $couponlimit; 
    $subscriptions[$itemname]       = $subscription;
    return;
 }

I am calling that function, like this:

 DefineSubscription(
                    "1",    // Item Name/Number
                    1,      // Subscription ID
                    1,      // Campaign Limit
                    30      // Coupon Limit
                    );

However, when I print_r($couponLimits);, I get Array.

The function and the Arrays are declared in a require_once'd file.

I am obviously doing something wrong.. But what? :)

EDIT: By doing the print_r in the DefineSubscription function itself, I got the correct output. It appears my arrays are not global when I am including it? Isn't it supposed to be?


if your using global vars you should adresse them with $GLOBALS to make sure your in the right context

$GLOBALS['campaignLimits']    = array();
$GLOBALS['couponLimits']      = array();
$GLOBALS['subscriptions']     = array();

function DefineSubscription () { ... }

DefineSubscription(...);

print_r($GLOBALS['campaignLimits']);

Regards Thomas


Array ( [1] => 30 )

I got that by print_r'ing $couponLimits ...

well i put the all in a page though...

try debugging by adding values on declarations, and print_r right after you require_once or try include instead...


The problem is the ambit. 1) You declare $couponLimits in the main program 2) LATER, when the function is called, you declare global $couponLimits 3) You call $couponLimits in the main page, it is refered to the local one, not the global.

If you want your "main" $couponLimits to be global, you must declare it as global.

global $campaignLimits;
global $couponLimits;
global $subscriptions;

insted of

$campaignLimits    = array();
$couponLimits      = array();
$subscriptions     = array();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜