Search code examples
phpvariablesdetect

Value of variable has not changed after assignment in function


I set the $fe variable like this:

<?php
    $fe = 0;
    echo '<font color="red">Alert! Site is still in development! Bugs will be fixed!<br>';
?>

<?php if ($_GET['p'] == "smoke") { ?>

<?php } elseif ($_GET['p'] == "heg") { ?>

<?php } elseif ($_GET['p'] == "flash") { ?>

<?php } elseif ($_GET['p'] == "molotov") { ?>

<?php } else { l(); } ?>

<?php function l() {
    $fe = 1;
    echo '<a href="../mirage?p=smoke">Smokes</a><br><a href="../mirage?p=heg">HEGs</a><br><a href="../mirage?p=flash">Flashes</a><br><a href="../mirage?p=molotov">Molotovs</a>';
} ?>

But then in the following code, the if ($fe == 0) block is always executed, whatever the parameter p was:

<div class="topleftcorner">
    <?php
        if ($fe == 0) {
            echo '<a href="../mirage"><-- Back</a>';
        } elseif ($fe == 1) {
            echo '<a href="../../csgo"><-- Back</a>';
        }
    ?>
</div>

What am I doing wrong?


Solution

  • The two $fe variables are not the same variable. This one:

    function l() {
        $fe = 1;
        //... etc
    }
    

    ... only exists in that function, it has nothing to do with the other, global one, and so $fe is still 0 for the last code block.

    A quick solution is to declare that variable as being the same, global variable, with the global keyword:

    function l() {
        global $fe;
        $fe = 1;
        //... etc
    }
    

    But one may wonder why you actually want to do this in a function.