PHP函数 - 在函数外部工作,但不在内部

时间:2015-03-20 00:08:17

标签: php function

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

当不在函数内时,页面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页面调用该函数,但似乎没有任何效果。

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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()将数组中的值放入单行中的标量变量中。

相关问题