I have the following PHP code, which is stored in a seperate PHP file to the index.php file I am using.
The page include()'s fine into the index.php file when not within a function.
$_3_dart_score = $_POST["user-input"];
$remaining_score = 501 - $_POST["user-input"];
However when it is included with an function, it doesn't seem to work.
<?php
function throw()
{
$_3_dart_score = $_POST["user-input"];
$remaining_score = 501 - $_POST["user-input"];
global $_3_dart_score
global $remaining_score
throw();
}
?>
I have tried all sorts, even calling the function from the index.php page, however nothing seems to work.
-
1Your function is calling itself which I highly doubt you wantJohn Conde– John Conde2015年03月20日 00:08:47 +00:00Commented Mar 20, 2015 at 0:08
-
Fair point. I will try again with a loop. Thankswardheed– wardheed2015年03月20日 00:09:12 +00:00Commented Mar 20, 2015 at 0:09
-
You don't really want a function accessing global variables like that. Pass them is as arguments, like: function throw($input, $otherinput) {...dudeman– dudeman2015年03月20日 00:11:40 +00:00Commented Mar 20, 2015 at 0:11
2 Answers 2
You need to call throw()
from outside of your function, not inside of it. You should also consider passing variables as arguments instead of relying on global variables.
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"]);
Get rid of the
global
nonsense. That's bad form. Instead return those values. I use an array so I can return both at once. (They actually should be done separately in different functions but you're not quite there yet).I pass
$_POST["user-input"]
as a parameter tothrow()
as your function should not be so closely tied to other code. This way that value can come from anywhere and this function will still work.I use
list()
to put those values in the array into there own scalar variables in a one-liner.