for循环和while循环中的变量范围 [英] Variable scope in for-loop and while-loop

查看:200
本文介绍了for循环和while循环中的变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PHP新手,我不明白为什么下面代码的最终结果是'233'而不是'231',是不是foreach中的$ a是一个临时变量?

 <?php 
$ a ='1';
$ c = array('2','3');
foreach($ c as $ a){
echo $ a;
}
echo $ a;
?>

任何人都可以帮忙吗? Thks。



更新2014-11-28
现在我知道我的问题是什么。正如接受的答案和这个答案所指出的那样, foreach 也不是而像函数一样,它们就像 $ a = '3'; 。所以现在我知道这是我的误解,它不只是关于 php ,因为我已经在python中试过了,它是相同的。






打印a
打印a
$ a $ 123
$


解决方案

code>在第一行, foreach()循环中的 $ a 是一个同一个对象。在循环结束后, $ a 的值为 3 ,这是 echo ed在上一个语句。
根据php.net:


大部分所有的PHP变量只有一个作用域。

只有在一个函数中,变量作用域是不同的。

这将产生你想要的结果'231':

  $ a ='1'; 
$ c = array('2','3');
函数iterate($ temp)
{
foreach($ temp as $ a)
echo $ a;
}
迭代($ c)
echo $ a;

因为在 iterate()函数中, $ a 独立于调用代码的 $ a

更多信息: a href =http://php.net/manual/zh/language.variables.scope.php =nofollow> http://php.net/manual/zh/language.variables.scope.php


I'm new in PHP, I don't understand why the final result of the code below is '233' instead of '231', isn't the $a in foreach is a temp variable?

<?php
    $a = '1';
    $c = array('2', '3');
    foreach($c as $a){
        echo $a ;
    }
    echo $a;
?>

Can anyone help? Thks.

Updated 2014-11-28 Now I know what was my problem. As the accepted answer and this answer have pointed out, neither the foreach nor the while act like functions, they are just normal sentences just like $a='3';. So now I know this is my misunderstanding and it's not just about php, as I've tried in python, it's the same.

a = 123
b = [1, 2, 3]
for a in b:
    print a
print a

解决方案

The $a on line 1 and the $a in the foreach() loop is one and the same object. And after the loop ends, $a has the value 3, which is echoed in the last statement.
According to php.net:

For the most part all PHP variables only have a single scope.

Only in a function does the variable scope is different.
This would produce your desired result '231':

$a = '1';
$c = array('2', '3');
function iterate($temp)
{
    foreach($temp as $a)
        echo $a ;
}
iterate($c)
echo $a;

Because in the iterate() function, $a is independent of the $a of the calling code.
More info: http://php.net/manual/en/language.variables.scope.php

这篇关于for循环和while循环中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆