HELP
HELP

Reputation: 14585

PHP global question

How can I use the global keyword so that when I press the submit button I can set the global keyword so that the top part of the script works?

located on top of the script.

if(!isset($u)){
    echo 'the $u has no value';
} else if(isset($u)){
    echo 'the $u has a value of yes';
}

located on bottom of the script.

if (isset($_POST['submit'])){
    global $u;
    $u = 'yes';
}

Upvotes: 0

Views: 85

Answers (3)

tato
tato

Reputation: 5569

global is related to scope, not to order of execution

If both pieces of code are global, i.e. are not contained into functions, the 'global' keyword has no effect, because they are in the same scope

As another answer has correctly pointed out, your problem is an order of execution problem, not a scope problem

Upvotes: 2

Jim
Jim

Reputation: 22656

That's not what global means. Global means that the variable can be accessed inside functions and the like. You probably want to use Sessions. This involves calling

sesssion_start();

somewhere (usually the top of your script). Variables can then be stored and retrieved by doing

$_SESSION['name'] = $foo;//Store a variable into the session
$bar = $_SESSION['bar'];//Retrieve a variable from the session

In your case you would store u variable into the session and retrieve it after the submit.

Is there some reason you aren't just passing this value via the form?

Upvotes: 1

Jan Sverre
Jan Sverre

Reputation: 4733

You have to run the

if (isset($_POST['submit'])){
    global $u;
    $u = 'yes';
}

before the

if(!isset($u)){
    echo 'the $u has no value';
} else if(isset($u)){
    echo 'the $u has a value of yes';
}

PHP reads the code line by line, so isset($u) always return FALSE until the line $u = 'yes'; is run.

Upvotes: 0

Related Questions