-1

I would elaborate further on this if I could, but the main problem I'm having is I can't access a variable outside of a function. I've tried both methods which I have below.

Here is my source:

function register($rand, $code) {
    global $rand, $access_token;
    if ($code == $access_token)
        $rand = rand('100000','1000000');
}   

echo $rand;

5 Answers5

1

may be it's help for you

function register($rand, $code) {
    global $rand, $access_token;
    if ($code == $access_token) {
        $rand = rand('100000','1000000');
    }



return $rand;
} 

echo register($rand, $code);

0
function register($rand, $code) {
    if ($code == $access_token)
        $rand = rand('100000','1000000');
}   

then call function first

register('1','2');
 echo $rand;
Jhonathan H.
  • 2,674
  • 1
  • 16
  • 26
  • Sorry, but when calling register(1,2), what do those numbers represent? Can't I just put register($rand) –  Mar 25 '13 at 06:13
  • means you are passing the value of $rand and $code parameter from your function.. – Jhonathan H. Mar 25 '13 at 06:14
  • You're method was effective, but DarkCthulhu said it best above. register(0) worked. –  Mar 25 '13 at 06:18
  • 1
    @ChristianRankin don`t worry both are still the same they just differ in there parameters Darkchuchu only pass 1 parameters but here you passed 2 parameters .Because your function above state that you must pass 2 certain parameters.. – Jhonathan H. Mar 25 '13 at 06:21
0

Please consider using arguments instead of using $GLOBALS or using global $var, because its recommended [take a look at these questions: one & two]

function register($rand, $code, $access_token) {
    if ($code == $access_token){
      $rand = rand('100000','1000000');
    }
    return $rand;
}

echo register($rand, $code, $access_token);
Community
  • 1
  • 1
0

I guess it should run ok, if you are calling function before accessing $rand variable.

function register($rand, $code) {
    global $rand, $access_token;
    if ($code == $access_token) {
        $rand = rand('100000','1000000');
    }
    echo "\nInside Function = ".$rand;
    echo $access_token;
}   

register(100, '');
echo "\nOutside Function = ".$rand;
Vinay
  • 2,465
  • 3
  • 23
  • 35
0

You have to call the function before $rand is set. Global $rand inside the function does not set any value before you call register().

<?php
    function register($rand, $code) {
        global $rand, $access_token;
        if ($code == $access_token)
            $rand = rand('100000','1000000');
    }   
    register('x', 'y');

    echo $rand;
?>

If PHP would set all global values before calling functions, then think of the following. What would $rand be set to? It only makes sense when one of the functions are called.

<?php
function a() {
global $rand = 1;
}
function b() {
global $rand = 2;
}
bestprogrammerintheworld
  • 5,018
  • 6
  • 36
  • 67