在函数内部分配变量时出现错误


Getting Error on Assigning Variable Inside a Function

你能看看这个脚本,让我知道为什么我得到

未定义变量:step1

错误呢?

<?php
$step1;
function getNums($num1, $num2){
 $diff = $num2 - $num1;
  $steps =[
        round($num1 + $diff/4), 
        round($num1 + $diff/2), 
        round($num1 + $diff*.75), 
        $num2
    ];
 $step1 = $steps[1];
}
getNums(50, 400);
echo $step1;
?>

函数内部的代码在不同的范围内,而不是在它外部运行的代码,这就是为什么你得到关于$step1未定义的错误-它在函数外部被定义。如果您希望能够在函数中引用它,您将需要通过引用将其作为参数传递给函数,或者使变量global

通过引用传递

function getNums( $num1, $num2, &$step1 ){
    // ... your code
}
// pass the variable by reference
getNums( 50, 400, $step1 );
echo $step1;

Using global

// accessible globally
global $step1;
function getNums( $num1, $num2 ){
    global $step1;
    // ... your code, with $step1 accessible
}
getNums( 50, 400 );
echo $step1;

为什么不通过引用传递呢?

<?php
$step1;
function getNums($num1, $num2, &$step1){
 $diff = $num2 - $num1;
  $steps =[
        round($num1 + $diff/4), 
        round($num1 + $diff/2), 
        round($num1 + $diff*.75), 
        $num2
    ];
 $step1 = $steps[1];
}
getNums(50, 400,$step1);
echo $step1;
?>

应该可以