I wrote a PHP global variable in the view of thinkPHP3.2.3, and I made an amazing discovery.
黄舟
黄舟 2017-06-08 11:01:45
0
2
601

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!

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
代言

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.

大家讲道理

Try it

<?php
    $x=10;
    $y=10;
    function add() use(&$x, &$y){
        $y=$x+$y;
    }
    add();
    echo $y;
?>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template