PHP - 调用一个没有 return 的函数,它确实改变了值

PHP - Call a function with no return that does actually change values

我想在 PHP 中调用一个函数,该函数更改现有变量而不返回特定变量。

举个例子:

<?php
  $number1 = 5;
  $number2 = 3;
  echo $number1;
  echo $number2; //shows the unmodified numbers

  modifyNumbers($number1, $number2); // Modifies the Numbers

  echo $number1;
  echo $number2; //shows the modified numbers
?>

<!-- Stuff -->

<?php
  function modifyNumbers($number1, $number2) {
    /* Doing math stuff with the numbers */
    /* No return because many numbers were changed / overwritten
  }
?>

基本上,我想创建一个只覆盖变量的函数,而不是将特定值返回给调用该函数的特定变量。

提前致谢!

在参数前加上一个符号。

function modifyNumbers(&$number1, &$number2) {
    /* Doing math stuff with the numbers */
    /* No return because many numbers were changed / overwritten
  }

这样,就创建了一个引用,您对变量所做的一切都会影响变量 'outside' 函数。

通过引用传递 &

<?php
  $number1 = 5;
  $number2 = 3;
  echo $number1;
  echo $number2; //shows the unmodified numbers

  modifyNumbers($number1, $number2); // Modifies the Numbers

  echo $number1;
  echo $number2; //shows the modified numbers
?>

<!-- Stuff -->

<?php
  function modifyNumbers(&$number1, &$number2) {
    $number1++;
    $number2--;
  }
?>