PHP在函数外工作,但不能在函数内工作


PHP works outside function, but not inside

我有下面的PHP代码,它存储在我正在使用的index.PHP文件的一个单独的PHP文件中。

当不在函数中时,page include()可以很好地放入index.php文件中。

  $_3_dart_score = $_POST["user-input"];
  $remaining_score = 501 - $_POST["user-input"];

然而,当它包含在函数中时,它似乎不起作用。

<?php
function throw()
{
$_3_dart_score = $_POST["user-input"];
$remaining_score = 501 - $_POST["user-input"];
global $_3_dart_score
global $remaining_score
throw();
}
?>

我尝试过各种方法,甚至从index.php页面调用函数,但似乎都不起作用。

您需要从函数外部而不是函数内部调用throw()。您还应该考虑将变量作为参数传递,而不是依赖全局变量。

function throw($input) {
    $_3_dart_score = $input;
    $remaining_score = 501 - $input;
    return array($_3_dart_score, $remaining_score);
}
list($_3_dart_score, $remaining_score) = throw($_POST["user-input"]);
  1. 去掉global的废话。这是一种糟糕的形式。相反,返回那些值。我使用了一个数组,这样我就可以同时返回这两个数组。(实际上,它们应该在不同的函数中单独完成,但您还没有完全做到)。

  2. 我将$_POST["user-input"]作为参数传递给throw(),因为您的函数不应该与其他代码紧密相连。通过这种方式,该值可以来自任何地方,并且该函数仍然有效。

  3. 我使用list()将数组中的这些值放入一行中自己的标量变量中。