I am creating a multipage form in PHP, using a session. The $stage variable tracks the user’s progress in filling out the form, (UPDATE) and is normally set in $_POST at each stage of the form.
On the second page (stage 2), the form’s submit button gets its value like this:
echo '<input type="hidden" name="stage" value="'; echo $stage + 1; echo '" />;
That works fine – $stage + 1 evaluates to 3 if I’m on page 2. But since I’m doing this more than once, I decided to pull this code out into a function, which I defined at the top of my code, before $stage is mentioned.
In the same spot where I previously used the code above, I call the function. I have verified that the function’s code is the same, but now $stage + 1 evaluates to 1.
Is PHP evaluating my variable when the function is defined, rather than when it’s called? If so, how can I prevent this?
Update 1
To test this theory, I set $stage = 2 before defining my function, but it still evaluates to 1 when I call the function. What’s going on?
Problem Solved
Thanks to everyone who suggested variable scope as the culprit – I’m slapping my forehead now. $stage was a global variable, and I didn’t call it $GLOBAL_stage, like I usually do, to prevent this sort of problem.
I added global $stage; to the function definition and it works fine. Thanks!
No, PHP will evaluate your variable when the function is called. But your function has a local variable scope, i.e. without seeing your function I’d guess that you are operating on a local variable. You can import global variables into you function although this is discouraged:
It’s really hard to say without knowledge of your code, but I’d go on to guess that you are using ‘register globals’ to inject your form parameters into global PHP variables ($state, in this case). You might want to consider turning
register_globalsoff because it really is a security risk and using the so-called superglobal variables instead.edit
Ok, so you’re seeing your stage in the $_POST array. Still wildly guessing about your function, you might try the following:
Suberglobals like the $_POST array don’t need to be declared with
global.