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

问题描述 投票:0回答:4

我试图更改在使用函数时声明的变量的值

<?php
$test = 1;
function addtest() {
    $test = $test + 1;
}
addtest();
echo $test;
?>

但似乎不能。只有在函数中声明为参数的变量才有效。有这方面的技术吗?预先感谢

php function variables
4个回答
5
投票

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

function addtest() {
    global $test; 
    $test = $test + 1;
}

使用全局变量有很多注意事项 -

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

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

这里有一个轻微的改进,不需要

global
-

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

echo $test; // 1
$foo = addtest($test);
echo $foo; // 2

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


0
投票

不确定这是否是一个人为的示例,但在这种情况下(与大多数情况一样),使用

global
将是极其糟糕的形式。为什么不直接返回结果并分配返回值呢?

$test = 1;
function increment($val) {
    return $val + 1;
}
$test = increment($test);
echo $test;

这样,如果您需要增加除 $test 之外的

任何其他 
变量,您就已经完成了。

如果您需要更改多个值并返回它们,您可以返回一个数组并使用 PHP 的

list
轻松提取内容:

function incrementMany($val1, $val2) {
    return array( $val1 + 1, $val2 + 1);
}
$test1 = 1;
$test2 = 2;

list($test1, $test2) = incrementMany($test1, $test2);
echo $test1 . ', ' . $test2;

您还可以使用

func_get_args
接受动态数量的参数并返回动态数量的结果。


0
投票

使用

global
关键字。

<?php
$test = 1;
function addtest() {
    global $test;
    $test = $test + 1;
}
addtest();
echo $test; // 2
?>

0
投票

也许你可以试试这个。

<?php 

function addTest(&$val){
  # Add this & and val will update var who call in from outside 
  $val += 1 ;
}

$test = 1;
addTest($test);
echo $test;

// 2 

$anyVar = 5;
addTest($anyVar);
echo $anyVar;

// 6
© www.soinside.com 2019 - 2024. All rights reserved.