php - 函数内部变量 incremented 的值为 1

标签 php scope

编辑:很抱歉,当我试图找出问题时,原始代码是一个迭代,我已经编辑了代码 This问题开始类似,但这是我遇到的真正问题:

在这段代码中:

<?php
    $a = 2:

    function incr(){
        $a++;
    echo $a;
    }

    echo $a;
    incr();
?>

输出是 2,然后是 1,这向我表明变量 $a 在函数内部被初始化为 0。服务器是否仅凭我使用增量语法将变量初始化为 0 就知道了?

最佳答案

$a 未定义,然后当您递增它时,它会变为 1

function incr(){
    $a++; // $a is undefined
    return $a;
}

正如 manual 中指出的那样:

Note:

The increment/decrement operators only affect numbers and strings. Arrays, objects and resources are not affected. Decrementing NULL values has no effect too, but incrementing them results in 1.

您可以使用 global,它会按预期返回。

function incr(){
    global $a;
    $a++;
    return $a;
}

关于php - 函数内部变量 incremented 的值为 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149339/

相关文章:

javascript - 在同一页面中两次使用 livesearch 文本框

php - SQL Select where IN (array) 仅当找到数组中的第一项时才返回

php - 我应该为 SEO 转换动态网址吗?

php - Codeigniter - 收到 404 Not Found 错误

java - Java 中数组与非数组对象的变量范围

javascript - Angular 如何以正确的方式从服务设置范围变量?

php - 如何在 mysql 中使用不同的选择子查询在表中插入行?

python - 在 exec 中用空局部变量列表理解 : NameError

php - 全局函数和将这样的函数包装到命名空间类中有什么区别吗?

python - for/if循环和python中变量的范围