簡體   English   中英

PHP函數-在函數外部起作用,但不在內部起作用

[英]PHP function - works outside function, but not inside

我有以下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頁面調用該函數,但是似乎沒有任何效果。

您需要從函數外部而不是函數內部調用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()將這些值放在數組中,並且在單行代碼中將它們放在自己的標量變量中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM