Note that there are some explanatory texts on larger screens.

plurals
  1. PODoes PHP evaluate variables when a function is defined?
    primarykey
    data
    text
    <p>I am creating a multipage form in PHP, using a session. The <code>$stage</code> variable tracks the user's progress in filling out the form, <strong>(UPDATE) and is normally set in $_POST at each stage of the form.</strong></p> <p>On the second page (stage 2), the form's submit button gets its value like this:</p> <pre><code>echo '&lt;input type="hidden" name="stage" value="'; echo $stage + 1; echo '" /&gt;; </code></pre> <p>That works fine - <code>$stage + 1</code> 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 <code>$stage</code> is mentioned.</p> <p>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 <code>$stage + 1</code> evaluates to 1.</p> <p><strong>Is PHP evaluating my variable when the function is defined, rather than when it's called? If so, how can I prevent this?</strong></p> <h3>Update 1</h3> <p>To test this theory, I set <code>$stage = 2</code> before defining my function, but it still evaluates to 1 when I call the function. What's going on?</p> <h3>Problem Solved</h3> <p>Thanks to everyone who suggested variable scope as the culprit - I'm slapping my forehead now. <strong><code>$stage</code> was a global variable, and I didn't call it <code>$GLOBAL_stage</code></strong>, like I usually do, to prevent this sort of problem.</p> <p>I added <code>global $stage;</code> to the function definition and it works fine. Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload