【问题标题】:PHP function - works outside function, but not insidePHP 函数 - 在函数外部工作,但不在内部
【发布时间】:2015-03-20 08:12:43
【问题描述】:

我有以下 PHP 代码,它存储在一个单独的 PHP 文件中,与我正在使用的 index.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 页面调用该函数,但似乎没有任何效果。

【问题讨论】:

  • 你的函数正在调用自己,我非常怀疑你想要的
  • 公平点。我会用循环再试一次。谢谢
  • 你并不真正想要一个访问全局变量的函数。将它们作为参数传递,例如: function throw($input, $otherinput) {...

标签: php function


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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() 将数组中的这些值放入单行中的自己的标量变量中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-24
      相关资源
      最近更新 更多