php使用函数来改变函数外部变量的值

Cud*_*doX 0 php variables function

我试图改变函数使用函数之外的声明变量的值

<?php
$test = 1;
function addtest() {
    $test = $test + 1;
}
addtest();
echo $test;
?>
Run Code Online (Sandbox Code Playgroud)

但它似乎不可能.只有在函数中声明为参数的变量才有效.这有什么技巧吗?提前致谢

Jay*_*ard 5

将函数内的变量更改为全局变量 -

function addtest() {
    global $test; 
    $test = $test + 1;
}
Run Code Online (Sandbox Code Playgroud)

使用全局变量有很多警告 -

  • 从长远来看,您的代码将难以维护,因为全局变量可能会对将来的计算产生不良影响,您可能不知道变量是如何被操纵的.

  • 如果你重构代码并且函数消失它将是有害的,因为$ test的每个实例都与代码紧密耦合.

这是一个小小的改进,不需要global-

$test = 1;
function addtest($variable) {
    $newValue = $variable + 1;
    return $newValue;
}

echo $test; // 1
$foo = addtest($test);
echo $foo; // 2
Run Code Online (Sandbox Code Playgroud)

现在您不必使用全局,并且在将新值分配给另一个变量时,您已根据自己的喜好操作$ test.