search

Home  >  Q&A  >  body text

I wrote a PHP global variable in the view of thinkPHP3.2.3, and I made an amazing discovery.

Using the thinkPHP3.2.3 framework, I wrote a very simple code in the view. The suffix of this view file is .html

<?php
    $x=10;
    $y=10;
    function add(){
        global $x,$y;
        $y=$x+$y;
    }
    add();
    echo $y;
?>

The echo result is 10. I don’t understand it. The result should be 20. I just wrote it again if I didn’t believe it, and it was still 10. I thought about it and wrote it into a separate php file, and the result was 20. Why is this? Do the views in thinkPHP not support PHP syntax? Please give me some advice!

黄舟黄舟2770 days ago607

reply all(2)I'll reply

  • 代言

    代言2017-06-08 11:03:45

    Obviously the $x, $y here are not global variables.
    So the global $x, $y in the function do not refer to the x, y above

    If you look at the compiled template file, you will find that this code should be included in a function.

    reply
    0
  • 大家讲道理

    大家讲道理2017-06-08 11:03:45

    Try it

    <?php
        $x=10;
        $y=10;
        function add() use(&$x, &$y){
            $y=$x+$y;
        }
        add();
        echo $y;
    ?>

    reply
    0
  • Cancelreply