dro59505
dro59505
2016-11-03 18:07

为什么PHP变量在循环周期内是持久的?

已采纳

The following code should never execute like that in any other language that I know (C, C++, C#, etc.)

<?php

$do = true;

for($i=0; $i<3; $i++) {
    if($do===true) {
        $some_variable = 666;
        echo $some_variable;
        $do = false;
    }
    if(isset($some_variable)) {
        echo $some_variable;
    }
}

Why PHP won't unset a $some_variable in next loop iteration?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • doudouwen2763 doudouwen2763 5年前

    Because it is set in the global scope. Once the first iteration sets it, the variable remains set.

    http://php.net/manual/en/language.variables.scope.php

    Here you can move the work to a function with its own scope. After the first iteration $do is set to false, and it no longer sets the variable:

    $do = true;
    
    function do_thing() {
        global $do;
        if($do===true) {
            $some_variable = 666;
            echo $some_variable;
            $do = false;
        }
        if(isset($some_variable)) {
            echo $some_variable;
        }
    }
    
    for($i=0; $i<3; $i++) {
        do_thing();
    }
    
    点赞 评论 复制链接分享
  • doutangu4671 doutangu4671 5年前

    Or, you can just make sure you unset the $some_variable in the first iteration.

    <?php
    
    $do = true;
    
    for($i=0; $i<3; $i++) {
    
        if($do===true) {
            $some_variable = 666;
            // echo $some_variable;
            $do = false;
        }
        if(isset($some_variable)) {
            echo $some_variable;
            unset($some_variable);
        }
    
    }
    
    ?>
    

    The point is that since you create the $some_variable in the first run of the loop, it will be available in all the subsequent runs of the loop, unless you specifically unset it again.

    点赞 评论 复制链接分享

相关推荐